Answer the question
In order to leave comments, you need to log in
Recursive Laravel category output?
Hello. I am making an online store on Laravel and already at the initial stage there was a snag: I don’t know how to display a list of categories. There is a categories table:
id - int
title - varchar
url - CNC
parent_id - parent ID and a Category
model class that has a getSubCategories method :
public function getSubCategories($categoryId)
{
return Category::where('parent_id', '=', $categoryId);
}
<Ul>
<li>Категория 1</li>
<li>Категория 2
<ul>
<li>Подкатегория 1</li>
<li>Подкатегория 2</li>
<li>Подкатегория 3
<ul>
<li>Подкатегория 1</li>
<li>Подкатегория 2</li>
<li>Подкатегория 3</li>
</ul>
</li>
</ul>
</li>
<li>Категория 3</li>
</Ul>
Answer the question
In order to leave comments, you need to log in
Get rid of the method, use link to yourself
public function children()
{
return $this->hasMany('Category', 'parent_id', 'id');
}
When sampling for optimization, you can use Category::with('children'). For output, it's better to write a recursive blade helper, or use a recursive include to check for children.
// template_name.blade.php
@foreach($items as $item)
@if ($item->children)
@include('template_name', ['items' => $item->children])
@endif
@endforeach
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question