Shorter syntax for whereHas with call back function in laravel

Created at 15-Sep-2021 , By samar

Shorter syntax for whereHas with call back function in laravel

With this article, we’ll look at some examples of how to address the "Shorter syntax for whereHas with call back function in laravel" problem.

Shorter syntax for whereHas with call back function in laravel
  • Shorter syntax for whereHas with call back function in laravel

    $posts = Post::whereHas('comments', function($query){
                $query->where('post_id', 1);
            })->get();
    
    //Shorter syntax      
    $posts = Post::whereRelation('comments', 'post_id', 1)->get();
    

    This code snippet will return the post details if there are comments regarding this particular post (post_id is 1 in comments table) exists in the comments table else it will return a blank array in laravel.

    It will also helps you to get the post record which has at least one comment in comments table

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.