phplaravelmenularavel-permission

Problem with spatie/laravel-menu and spatie/laravel-persmissions


I'm using spatie/laravel-menu and spatie/laravel-persmissions in my laravel project.

I have created a permission, assigned it to a role, and assigned the role to my user. This works fine. Then I have generated a menu the middleware way using a macro like so:

\Menu::macro('main', function () use ($request) {
    return \Menu::new()
        ->withoutWrapperTag()
        ->withoutParentTag()
        ->setActiveClassOnLink()
        ->route('preparation', 'Anstehende Termine')
        ->route('postprocessing', 'Nachbereitung')
        ->routeIfCan('administrate', 'protocols', 'Protokolle')
        ->addItemClass('nav-link')
        ->setActive($request->url());
});

In my application I have two User models with different connections: App\User; using connection_a with database db_a and App\DirectoryA\User; using connection_b with database db_b

In the auth config the first one is defined, and using Auth::user()->can('administrate') works fine, even in the Middleware that defines the menu.

Since I have added the menu item via routeIfCan, I'm getting an error. It tells

Base table or view not found: 1146 Table 'db_b.permissions' doesn't exist (SQL: select permissions.*, model_has_permissions.model_id as pivot_model_id, model_has_permissions.permission_id as pivot_permission_id, model_has_permissions.model_type as pivot_model_type from permissions inner join model_has_permissions on permissions.id = model_has_permissions.permission_id where model_has_permissions.model_id = 1 and model_has_permissions.model_type = App\User)

What is going wrong here? It should use the App\User model. Placing a dd() at the point the framework throws the exception shows me the correct connection...

Please help.


Solution

  • A member of spatie helped to solve the problem:

    Under the hood, routeIfCan calls app(Gate::class)->allows($ability, $ablityArguments). I assume Gate behaves slightly different than Auth::user() when it comes to multiple guards. I don't see much room in routeIfCan to add an additional $guard or $connection argument, so I suggest you use $menu->addIf(Auth::user()->can('administrate'), ...) instead.