How to get all posts which contains comments in laravel

Updated at 14-Sep-2021, By samar

How to get all posts which contains comments in laravel

In this session, we’ll try our hand at solving the "How to get all posts which contains comments in laravel" puzzle by using the computer language.

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.
  • Get all posts which contains comments in laravel

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

    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