Reputation: 119
I have category table with is_featured column. now I want o select featured categories with 3 product (limit 3 or every featured category). I tried with following code but getting only 3 product from first featured category.
$categories = Category::where('is_featured', true)->with('products', function ($query){
$query->take(3);
})->get();
Can anyone help me to figure out this? Thanks in Advance
Upvotes: 1
Views: 2746
Reputation: 15319
Look like by default its not supported Eager-loading with a limit
To solve this problem you can install following library
https://github.com/staudenmeir/eloquent-eager-limit
and use following trait in both the model
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
if you are looking for without library then
Ref:Laravel Eloquent limit results for relationship
Ref:Eager-loading with a limit on collection only loads for last element in collection
https://github.com/laravel/framework/issues/18014
Upvotes: 1