Skip to content
Advertisement

Laravel Eloquent – how to get only 2 child of each parent using Eloquent?

I want to get category with only 2 subcategory not all subcategory. Like below output

JavaScript

Total 5 category and each category have 5 subcategory

Category.php

JavaScript

Subcategory.php

JavaScript

HomeController.php

Method 1:

JavaScript

Method 2:

JavaScript

But it get only 2 subcategory in first category.

Click here to view output

Please help me, How to get?

Advertisement

Answer

you can use the trait: HasEagerLimit:

you can install it:

JavaScript

and then in your model:

JavaScript

and also in SubCategory model:

JavaScript

now : when you load your relation … it should return the result you desire:

JavaScript

more details in: https://github.com/staudenmeir/eloquent-eager-limit

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement