Shorter syntax for whereHas with call back function in laravel

Updated at 14-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