I want to get category with only 2 subcategory not all subcategory. Like below output
JavaScript
x
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
JavaScript
class Category extends Model {
public function subcategory(){
return $this->hasMany('AppSubcategory');
}
public function limitSubcategory(){
return $this->hasMany('AppSubcategory')->limit(2);
}
}
Subcategory.php
JavaScript
class Subcategory extends Model {
public function category(){
return $this->belongsTo('AppCategory');
}
}
HomeController.php
Method 1:
JavaScript
Category::with(['limitSubcategory' => function($query) {
}])->get();
Method 2:
JavaScript
Category::with(['subcategory' => function($query) {
$query->limit(2);
}])->get();
But it get only 2 subcategory in first category.
Please help me, How to get?
Advertisement
Answer
you can use the trait: HasEagerLimit:
you can install it:
JavaScript
composer require staudenmeir/eloquent-eager-limit:"^1.0"
and then in your model:
JavaScript
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:
JavaScript
class Category extends Model {
use StaudenmeirEloquentEagerLimitHasEagerLimit;
}
now : when you load your relation … it should return the result you desire:
JavaScript
$results=Category::with('limitSubcategory')->get();
more details in: https://github.com/staudenmeir/eloquent-eager-limit