laravel-menu icon indicating copy to clipboard operation
laravel-menu copied to clipboard

build menu with nested categories from database

Open schel4ok opened this issue 2 years ago • 1 comments

I cannot understand how to build menu with nested categories from database. I have categories build with laravel-nestedset

So normally I can build tree-like menu with this code

in controller

$categories= $this->furnituraCategoryRepository->getTree();

in blade

@php

	$traverse = function ($categories) use (&$traverse) {
		echo '<ul class="list-disc ml-4">';
	    foreach ($categories as $category) {
	        echo '<li>'.$category->title;
	        
			if (count($category->children) > 0) {
				$traverse($category->children);
			}

	        echo '</li>';
	    }
	    echo '</ul>';
	};

	$test = $traverse($items);

@endphp

{{ $test }}

But with laravel-menu I cannot catch how to assemble this recursive function. I tried like this, but it gives me error Value of type null is not callable pointing on $traverse($category->children, $a);

    public function handle(Request $request, Closure $next)
    {

        $categories = $this->CategoryRepository->getTree();

        $traverse = function ($categories, $menu) use (&$traverse) {
            foreach ($categories as $category) {  

                if (count($category->children) > 0) {
                    $menu->group(['prefix' => $category->slug], function($m) use ($category) {
                        $m->add($category->title, '');
                        $m->group(['prefix' => $category->slug], function($a) use (&$traverse, $category) {
                            $traverse($category->children, $a);
                        });
                    });
                }

                $menu->add($category->title, $category->slug);
            };
        };


        Menu::make('Mytopmenu', function($menu) use ($traverse, $furnitura) {
            echo $traverse($furnitura, $menu);
        });

        return $next($request);
    }

schel4ok avatar May 18 '22 20:05 schel4ok

This looks like an error with your code, and not so much an error with the library.

Perhaps try removing the recursive requirement and iterating instead, or separating the function declaration out to a class level function, rather than a variable function. I can't help troubleshoot this. :)

dustingraham avatar May 19 '22 16:05 dustingraham