G
G
GaserV2016-10-01 12:42:57
Laravel
GaserV, 2016-10-01 12:42:57

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

1 answer(s)
A
Alex Wells, 2016-10-01
@Alex_Wells

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 question

Ask a Question

731 491 924 answers to any question