2
votes

I have installed backpack 4 and Spatie. https://github.com/spatie/laravel-permission

I have created 2 roles: Admin and Users in my back end admin panel(the CRUD that comes with Backpack).

I have then added 2 permissions: 1 called "read admin link" 1 called "read user link"

I have assigned the permissions to each role: read admin link = role of admin read user link = role of user

I see the permissions correctly assigned to the roles inside the admin panel.

Now on the left navbar, I would like to see 1 menu when logged as an admin or see another menu when logged as a user.

But I cannot get it to work:

<li> 
<ul>
@if(auth()->backpack_user()->can('read admin link'))
<li class="nav-item"><a class="nav-link" href=""><i class="nav-icon fa fa-user"></i> <span>Can only 
be seen by admins</span></a></li>
@endif
@if(auth()->backpack_user()->can('read user link'))
<li class="nav-item"><a class="nav-link" href=""><i class="nav-icon fa fa-user"></i> <span>Can only 
be seen by users</span></a></li>
@endif
</ul>
</li>

It seems that this permission checker(while logged in) :

@if(auth()->backpack_user()->can('xxxxxxxxxxx'))
@endif

Cause this error:

Facade\Ignition\Exceptions\ViewException
Method Illuminate\Auth\SessionGuard::backpack_user does not exist. (View: 
C:\laragon\www\demo\resources\views\vendor\backpack\base\inc\sidebar_content.blade.php)

This is my base.php setup:

'middleware_class' => [
    App\Http\Middleware\CheckIfAdmin::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    // \Backpack\CRUD\app\Http\Middleware\UseBackpackAuthGuardInsteadOfDefaultAuthGuard::class,
],

Any idea why this is happening please?

Thank you

1
Auth::guard('backpack')->user()Alec Joy
This I think is ok inside a controller but not into blade templates.Benny
If it's giving you an error just put a \ in front of itAlec Joy
ok i think I was using the permission in the wrong way. In blade you have to check for the role and not the permissions I think as this works fine in blade: @if(backpack_user()->hasRole('Admin'))Benny
I believe the permissions are only for the routes or controllersBenny

1 Answers

2
votes

Ok here is the fix:

You need to add the last line(class)

        'middleware_class' => [
            App\Http\Middleware\CheckIfAdmin::class,
           \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\Backpack\CRUD\app\Http\Middleware\UseBackpackAuthGuardInsteadOfDefaultAuthGuard::class,
],

Then you must delete the current roles in the database or they will keep the old "web" guard settings. Delete them and recreate them with this new backpack guard and everything will work fine.