How can i get latest n number of related model records in laravel

Viewed 86

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;

2 Answers

If your n stays constant, for example: getting the latest 3 comments, you can set up the relation in the model this way:

public function latestComments() {
    return $this->hasMany(Comment::class)->latest()->take(3);
}

In your controller, you can simply use:

$posts = Post::with('latestComments')->get();

If your n keeps changing, you can follow this thread: Link

Related