2

I have two tables - Posts and Comments. The relationship between them is one-to-many. A Post has many comments.

I am trying to get a list of all Posts with their latest 2 Comments

I have tried this:

$posts = Post::with(['comments'=>function($query){
    $query->latest()->take(2)->get();
}])->get();

But it seems to be working only for the first Post;

Mostafa Abedi
  • 521
  • 6
  • 18
  • similar issue this might help you. Ref:https://stackoverflow.com/questions/68422673/sub-query-with-eloquent-relationship/68422825#68422825 – John Lobo Jul 21 '21 at 03:06

1 Answers1

1

Laravel doesn't offer this functionality out of the box as discussed here https://github.com/laravel/framework/issues/18014 and documented here https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads, but there is a package that you can use to achieve this.

Take a look at https://github.com/staudenmeir/eloquent-eager-limit

Abishek
  • 10,615
  • 18
  • 69
  • 108