Answer the question
In order to leave comments, you need to log in
How to correctly display child categories?
Tell. There is a categories table: id, title, slug, parent; parent contains the id(int) of the parent category. So. Of course you can take where('id', '=', 'parent'); The child categories will return. But what if a child category has more children? You can make several arrays, but I think you don’t need to do this and there is some more universal solution) please help.
Answer the question
In order to leave comments, you need to log in
Code stubbed from stackoverflow:
public static function ancestors($id)
{
$ancestors = Model::where('id', '=', $id)->get();
while ($ancestors->last()->parent_id !== null)
{
$parent = Model::where('id', '=', $ancestors->last()->parent_id)->get();
$ancestors = $ancestors->merge($parent);
}
return $ancestors;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question