DEV Community

Morcos Gad
Morcos Gad

Posted on • Edited on

Quick Tips (2) - Laravel

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();
});
Enter fullscreen mode Exit fullscreen mode
  • 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
            });
Enter fullscreen mode Exit fullscreen mode
  • 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');
Enter fullscreen mode Exit fullscreen mode
  • Route resources grouping
Route::resources([
    'photos' => PhotoController::class,
    'posts' => PostController::class,
]);
Enter fullscreen mode Exit fullscreen mode
  • 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',
]; 
*/
Enter fullscreen mode Exit fullscreen mode
  • Route model binding soft-deleted models
Route::get('/posts/{post}', function (Post $post) {
    return $post;
})->withTrashed();
Enter fullscreen mode Exit fullscreen mode
  • 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
        });
Enter fullscreen mode Exit fullscreen mode
  • 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',
]);
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code.

Top comments (0)