1

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

Eva Glaude
  • 99
  • 1
  • 11
  • Dub: https://stackoverflow.com/questions/49731582/laravel-eloquent-limit-in-relation-that-has-sub-relation – Maksim Jul 17 '21 at 17:32

1 Answers1

1

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

John Lobo
  • 14,355
  • 2
  • 10
  • 20