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

Category 1
  subcategory 1, 
  subcategory 2,
Category 2
  subcategory 1,
  subcategory 2, 
Category 3
  subcategory 1,
  subcategory 2

Total 5 category and each category have 5 subcategory

Category.php

class Category extends Model {
    public function subcategory(){
        return $this->hasMany('AppSubcategory');
    }

    public function limitSubcategory(){
        return $this->hasMany('AppSubcategory')->limit(2);
    }
}

Subcategory.php

class Subcategory extends Model {
    public function category(){
        return $this->belongsTo('AppCategory');
    }
}

HomeController.php

Method 1:

Category::with(['limitSubcategory' => function($query) {

}])->get();

Method 2:

Category::with(['subcategory' => function($query) {
   $query->limit(2);
}])->get();

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:

composer require staudenmeir/eloquent-eager-limit:"^1.0"

and then in your model:

class Category extends Model {
use StaudenmeirEloquentEagerLimitHasEagerLimit;

    public function subcategory(){
        return $this->hasMany('AppSubcategory');
    }

public function limitSubcategory(){
    return $this->hasMany('AppSubcategory')->limit(2);
}
}

and also in SubCategory model:

class Category extends Model {
use StaudenmeirEloquentEagerLimitHasEagerLimit;
}

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

$results=Category::with('limitSubcategory')->get();

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

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