How to implement multi-level menu in Laravel + Database?

0

I'm having trouble implementing a multi-level menu with a database in Laravel. I even managed to print the menu for the first and second level, however, I would like to have any menu level without having to fiddle with the code for each new level.

I'm using this project to build the menu: link

Migration :

Schema::create('menus', function (Blueprint $table) {
    $table->increments('id');
    $table->string('title', 150);
    $table->string('slug', 150)->unique();
    $table->unsignedInteger('parent_id')->default(0);
    $table->smallInteger('order')->default(0);
    $table->boolean('enabled')->default(1);
    $table->timestamps();
});

Model :

class Menu extends Model
{
    public function parent()
    {
        return $this->belongsTo('App\Menu', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('App\Menu', 'parent_id');
    }
}

\ App \ Http \ Middleware \ GenerateMenus.php :

namespace App\Http\Middleware;

use Menu;
use Closure;
use App\Menu as DBMenu;

class GenerateMenus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {  
        $categories = DBMenu::with('children')->where('parent_id','=',0)->get();

        Menu::make('MyNavBar', function ($menu) use ($categories) {

            foreach($categories as $item) {
                if($item->children->count() > 0) {
                    $menu->add($item->title, $item->slug);
                    foreach($item->children as $submenu) {
                        $menu->get($item->slug)->add($submenu->title, $submenu->slug);
                    }
                } else {
                    $menu->add($item->title, $item->slug);
                }
            }
        });

        return $next($request);
    }
}

\ App \ Http \ Kernel ;

Within the web middleware I added the entry:

\App\Http\Middleware\GenerateMenus::class,

In view I call the menu like this:

{!! $MyNavBar->asUl() !!}
    
asked by anonymous 29.08.2018 / 21:55

0 answers