I talked about this great resource https://github.com/LaravelDaily/laravel-tips a while ago in a previous article https://dev.to/morcosgad/quick-tips-laravel-3n1e because it contains a lot of great tips that will help you do your project better and I have just released this new video https://www.youtube.com/watch?v=gyQnnT1Topw and
https://www.youtube.com/watch?v=hEmi12wNGas and
https://www.youtube.com/watch?v=mJWHv_YBC7o with some great tips that I wanted to share with you.
- Skip method
$schedule->command('emails:send')->daily()->skip(function () {
return Calendar::isHoliday();
});
- When searching for the first record, you can perform some actions
$book = Book::whereCount('authors')
->orderBy('authors_count', 'DESC')
->having('modules_count', '>', 10)
->firstOr(function() {
// THe Sky is the Limit ...
// You can perform any action here
});
- Make use of the value method on the query builder
// Before (fetches all columns on the row)
Statistic::where('user_id', 4)->first()->post_count;
// After (fetches only `post_count`)
Statistic::where('user_id', 4)->value('post_count');
- Route resources grouping
Route::resources([
'photos' => PhotoController::class,
'posts' => PostController::class,
]);
- Get all the column names for a table
DB::getSchemaBuilder()->getColumnListing('users');
/*
returns [
'id',
'name',
'email',
'email_verified_at',
'password',
'remember_token',
'created_at',
'updated_at',
];
*/
- Route model binding soft-deleted models
Route::get('/posts/{post}', function (Post $post) {
return $post;
})->withTrashed();
- Specify what to do if a scheduled task fails or succeeds
$schedule->command('emails:send')
->daily()
->onSuccess(function () {
// The task succeeded
})
->onFailure(function () {
// The task failed
});
- Validation is required if another field is accepted
Validator::make([
'is_company' => 'on',
'company_name' => 'Apple',
], [
'is_company' => 'required|boolean',
'company_name' => 'required_if_accepted:is_company',
]);
- Redirect with URL fragment
return redirect()
->back()
->withFragment('contactForm');
// domain.test/url#contactForm
return redirect()
->route('product.show')
->withFragment('reviews');
// domain.test/product/23#reviews
I hope you enjoyed the code.
Top comments (0)