T
T
turindd2021-07-21 07:27:45
Laravel
turindd, 2021-07-21 07:27:45

How to build back menu in laravel?

Hello.

I'm trying to assemble the reverse menu on the chest. Chet doesn't work!
the last subcategories come to me, for example (highlighted in bold):
clothes->women's-> jeans
clothes->women's-> pants
clothes->men's-> casual-> jeans clothes-> men's-
>casual-> trousers

collection of all categories!

I try like this:

function catNet($categories, $array = null){
            //$array = $categories;
            if($array == null){
                //dd(1);
                $array = collect();
                foreach ($categories as $category){
                    if($category->parent AND !$categories->firstWhere('id', $category->parent->id)){
                        $categories = $categories->add($category->parent);
                        $array = $array->add($category->parent);
                    }
                }
                return catNet($categories,$array);
            }elseif(!$array->isEmpty()){
                //dd(2);
                foreach ($array as $category){
                    if($category->parent AND !$categories->firstWhere('id', $category->parent->id)){
                        $categories->add($category->parent);
                        $array->add($category->parent);
                    }
                }
                return catNet($categories,$array);
            }else{
                //dd(3);
                return $categories;
            }

        }

        $res = catNet($categories);
        dd($res);


If possible, please tell me how to assemble but with closure functions (for myself):
I try it doesn’t work either
$result2 = function ($item) use ($categories){
            if($item->parent && !$categories->firstWhere('id', $item->parent->id)){
                $categories->add($item->parent);
            }
        };

        $categories->each(function ($item) use ($result2){
            $result2($item);
        });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-07-21
@turindd

Nothing is clear in your code and description, but usually this task is solved like this:

$menu = [$category];

$parent = $category->parent;

while ($parent) {
  $menu[] = $parent;

  $parent = $parent->parent;
}

$menu = array_reverse($menu);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question