Hasan Setiawan

Write, write, write give your wings on code!

Follow me on GitHub

Playing with Eloquent object relations

You can use Eloquent limit into object relations query. By limiting results for a object relationship in a query help you on eager loading in Laravel

Let say we have a post model, which has many comments. And we want to show the first comment for every post on a list that shows all posts. In the post model, we 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);
}
              
            

You also can put Where in hasMany Relation. In case you willing do filter data in your relation table.

              
// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();