Peasant King
Peasant King

Reputation: 1

Dynamic menus from database in laravel using lavary/laravel-menu

I have a laravel application with static menus. Now I want to change this into dynamic menus from the database. So far so good so I made a migration for a table called menu_items.

Then I wrote a middleware with following handle method:

public function handle($request, Closure $next)
{
    \Menu::make('mainmenu', function ($menu) {

        $items = MenuItem::all();

        foreach ($items as $item) {

            if ($item->parent_id == null) {

                $menu->add($item->title, $item->link)
                    ->prepend('<i class="'.$item->icon.'"></i>');    
            }
            else {
                // dd($menu);
                $parent = $item->parent_id - 1;
                $menu->find($parent)->add($item->title, $item->link);
            }
        }

    return $next($request);
}

I changed to lavary/laravel-menu and try to get submenus added to the parent menu item dynamically. I do not understand why laravel always tells me at

$menu->find($parent)->add($item->title, $item->link);

Call to a member function add() on null $parent is not null if I print out with dd() If I do something like $menu->last()->add($item->title, $item->link); It works but thats not what I want...

Upvotes: 0

Views: 1989

Answers (1)

Loctarogar
Loctarogar

Reputation: 620

Probably you have to write function in your controller, and return variable to template? How will you access {{ Menu::main() }}?

$menu = Menu::build($menu_items, function ($menu, $menu_item) {
        $menu->link($menu_item->title, $menu_item->link);

{{ $menu->whatDoYouNeedToAccess }}

Upvotes: 1

Related Questions