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