Limit results for a hasMany relationship in a query for eager loading in Laravel

In one of the projects we are creating for a customer, I have a hasMany realationship between two models.
In one of my views, I list all the records of the models, which has many of the other model. But in this view I don't want to get all the relations, but only the first relation for each record. There are no good solution to do this, beacause if you try to add ->first() to the with() function (see this post about eager loading in Laravel), it will only take the first of the first record.

But I found a way to solve this problem.

I can add as many relations in the model as I wish, so I just added a new relation for the same model, but this time I took a hasOne instead:

An example:

I have a post model, which has many comments. And I want to show the first comment for every post on a list that shows all posts.

In the post model, I add these relations:

// Each post has many comments
public function comments() {
   return $this->hasMany('Comment');
}
// Get first comment
public function comment() {
   return $this->hasOne('Comment');
}

I can then use the comments relation when I want all the comments, but now I can also just choose to use the comment relation to only get one comment.

Alternatively, if I want the first three comments for each post I can add this relation:

// Get first 3 comments
public function threeComments() {
   return $this->hasMany('Comment')->limit(3);
}

Inspiration is taken from this post: http://laravel.io/forum/04-05-2014-eloquent-eager-loading-to-limit-for-each-post

ms@morningtrain.dk'

Martin Schadegg Rasch Jensen

  • Guillaume Olejniczak

    Thanks ! Nice thinking here ! Simple and effective

  • webicy

    Thanks. this has helped me alot

  • Thanks 🙂

  • malhal

    Your threeComments method actually limits the overall number of comments to 3 not 3 for each post.

  • sahed sawon

    Your threeComments method actually limits the overall number of comments

  • thank you su much.

  • thanks for this beautiful post. It was very descriptive.

  • thakns bro

  • Pinoy Camper

    For a single post this is okay. But if you use get (for all), the overall result will only include 3 comments

  • Manoj Kiran A

    It will work only if collection has one record. Otherwise it will fail