You need to load 12 collections with max of 4 posts in each collection ?
For this you need a third party package https://github.com/staudenmeir/eloquent-eager-limit
I'm trying to fetch categories (which I call collections) with 4 posts each. The below code works, but it's querying all the posts first, then only takes 4. With a lot of posts in each category, that's a lot of db queries. Is there a way to do it better?
My current Controller:
// CollectionController
public function index()
{
$collections = Collection::with('posts')->take(12)->get()->map(function($collection) {
$collection->setRelation('posts', $collection->posts->take(4));
return $collection;
});
return view('collections.index', compact('collections'));
}
And my model relations:
// Post Model
public function collection()
{
return $this->belongsTo(Collection::class);
}
// Collection Model
public function posts()
{
return $this->hasMany(Post::class);
}
You need to load 12 collections with max of 4 posts in each collection ?
For this you need a third party package https://github.com/staudenmeir/eloquent-eager-limit
Please or to participate in this conversation.