A
A
Aleksei2020-07-10 21:28:55
Laravel
Aleksei, 2020-07-10 21:28:55

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>';
     }


As I understand it, you can iterate and then cycle through all the upper parent categories to the main one.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aleksei, 2020-07-11
@axelprox

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;
        }
}

Controller:
$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>';

Ps I display directly in the controller, since ajax xhr (jquery) accesses it.
In the call, respectively, if we want to expand the order, then we use
reverse()
If we want to add the current selected category, then
push($id)
For connoisseurs there is a question why the model did not give out that the class was not found if it was
return $this->belongsTo('Categories', 'parent_id');

and all the way is ok
return $this->belongsTo('\App\Categories', 'parent_id');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question