Shorter syntax for whereHas with call back function in laravel

Shorter syntax for whereHas with call back function in laravel

Answers 1
  • 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();
    
    0

    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