Answer the question
In order to leave comments, you need to log in
Outputting subcategories in Laravel?
how to get rid of so many queries when displaying subcategories Category
model
class Category extends Model
{
protected $table = 'categories';
protected $fillable = [
'image','parent','sort_order','published'
];
public function description()
{
return $this->hasOne(CategoryDescription::class);
}
public function childrens()
{
return $this->hasMany(Category::class, 'parent');
}
}
$categories = Category::where('parent','=',0)->with(['childrens','description' => function($query){
$query->where('language_id', '=', Session::get('lnaguage_id));
}])->get();
$view->with([
'categories' => $categories,
]);
@foreach($categories as $category)
@if($category->childrens)
<div class="menu-sub divany-i-kresla" id="menu-{{$category->id}}" data-category="{{$category->slug}}">
<button class="btn-close btn-close_sub_menu">
<svg><use href="#close"></use></svg>
</button>
<div class="menu-sub_title">
<a href="/categories/{{$category->slug}}">{{$category->description->name}}</a>
</div>
<ul class="menu-sub_categories">
@foreach($category->childrens as $children)
<li>
<a href="/categories/{{$category->slug}}/{{$children->slug}}">
<img src="{{$children->image}}" alt="{{$children->description->name}}">
<span>{{$children->description->name}}</span>
</a>
</li>
@endforeach
</ul>
</div>
@endif
@endforeach
Answer the question
In order to leave comments, you need to log in
I don’t know how true, but in the Category model I did this
public function childrens()
{
return $this->hasMany(Category::class, 'parent')->with('description');
}
Check out this package for how it's done. There is what you need: https://github.com/lazychaser/laravel-nestedset
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question