I have users, images and image_user tables. I am trying to eager load and get all the user with images but limit images to only 4.
Think of it as a gallery. Where user can have one or many images
User Model
public function images()
{
return $this->belongsToMany(Images::class);
}
This is my query so far.
User::with(['images' => function ($query) {
$query->limit(4);
}
])->get();
This query returns user but with empty relationship (images)
Any help would be appreciated.
Cheers
There's no easy built-in way to do this.
Check out Jarek Tkaczyk's excelent post on this subject:
How to get N related models per parent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With