Answer the question
In order to leave comments, you need to log in
How to get parent categories for current subcategory in Laravel?
There is a table Categories(id, parent_id, name):
The goal is to display something like this from the controller:
Current section:
Electronics>Computers>Components>Video cards (we are here)
Accordingly, Video cards parent_id points to Accessories, they, in turn, to Computers, until the main category is will output parent_id=0.
I get the current category like this
public function listCategories(Request $request)
{
$catID = $request->id;
$currentCat = \App\Categories::find($catID);
// Текущий путь
echo '<h5>Текущий путь: '.$currentCat->name.'</h5>';
}
Answer the question
In order to leave comments, you need to log in
Solution found:
Model:
class Categories extends Model
{
public function parent()
{
return $this->belongsTo('\App\Categories', 'parent_id');
}
// Add this line if you want the "parents" property to be populated all the time.
protected $appends = ['parents'];
public function getParentsAttribute()
{
$collection = collect([]);
$parent = $this->parent;
while($parent) {
$collection->push($parent);
$parent = $parent->parent;
}
return $collection;
}
}
$currentCat = \App\Categories::find($catID);
$parentCats = Categories::find($catID)->parents->reverse()->push($currentCat);
echo '<h5> Выбор раздела';
foreach ($parentCats as $path) {
echo ' > '.$path->name_ru;
}
echo '</h5>';
reverse()
push($id)
return $this->belongsTo('Categories', 'parent_id');
return $this->belongsTo('\App\Categories', 'parent_id');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question