How to get all posts which contains comments in laravel

Sometimes you have to get all the posts which contains comments in laravel. You have to use the whereHas() method with relationship name to get all the records which have records that exist in the relationship (child) table using foreign key relation.

Answers 1
  • Get all posts which contains comments in laravel

    $posts = Post::whereHas('comments')->get();
    dd($posts);
    
    0

    This code snippet will return all the posts which has at least one comment exists in comments table.

  • Back to code snippet queries related laravel