Followings are some of useful code snippets of Laravel:
1). Show validation errors in view:
@if($errors->has())
@foreach ($errors->all() as $error)
<div>{{ $error }}</div>
@endforeach
@endif
2) Prevent errors by using the optional helper:
When accessing object values, if that object is null, your code will raise an error. A simple way of avoiding errors is to use the optional Laravel helper. see below example:
return optional($data)->total;
3) Make Copy of a Row:
See below example to make a copy of database entry using Replicate method:
$post = Posts::find(1);
$newPost = $post->replicate();
$newPost->save();
4) Using Default SQL Queries:
If you want to run a simple SQL query, without getting any results – like changing something in DB schema, you can just do DB::statement(). see below example:
DB::statement('drop table users');
5) Blade @auth
Instead of using if condition to check logged in user, you can use @auth directive. see below example:
@if(auth()->user())
// The user is authenticated.
@endif
6) Test email into laravel log file:
If you want to test email in your laravel app but unable to set up something like Mailgun, You can use .env parameter MAIL_DRIVER=log and all the email will be saved into storage/logs/laravel.log file, instead of actually being sent.
7) Generate Images with Seeds/Factories:
You can generate images with factories. see below example:
$factory->define(Post::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => bcrypt('password'),
'remember_token' => Str::random(10),
'avatar' => $faker->image(storage_path('images'), 50, 50)
];
});
8) Laravel Clear Cache:
You can clear cache from one place instead of running multiple artisan commands. Go to your routes/web.php file and add below code.
<?php
Route::get('/clear-cache', function() {
$exitCode = Artisan::call('config:cache');
$exitCode = Artisan::call('cache:clear');
$exitCode = Artisan::call('view:clear');
$exitCode = Artisan::call('route:cache');
});
Now open up your browser and add this route like below.
https://your_site_url/clear-cache
Hope this helps!
