Sam
Sam

Reputation: 997

Laravel and Spatie Permissions plugin update not working

I've performed a long-overdue update on a Laravel project from v5.7 (with Spatie Permissions 2.21) to v9 with Spatie 5.5.0. I'm not getting any error but the hasRole() function no longer ever returns true for users who definitely have the role. Echoing Auth::user()->getRoleNames() for the user just returns an empty array. Any guidance would be greatly appreciated.

Looking at my old commits, it seems that aside from the composer.json additions and database migrations, that only things I needed to do were a User model edit:

...
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasRoles;
...

And this config/permission.php (comments stripped):

<?php
return [
    'models' => [
        'permission' => Spatie\Permission\Models\Permission::class,
        'role' => Spatie\Permission\Models\Role::class,
    ],
    'table_names' => [
        'roles' => 'roles',
        'permissions' => 'permissions',
        'model_has_permissions' => 'model_has_permissions',
        'model_has_roles' => 'model_has_roles',
        'role_has_permissions' => 'role_has_permissions',
    ],
    'column_names' => [
        'role_pivot_key' => null, //default 'role_id',
        'permission_pivot_key' => null, //default 'permission_id',
        'model_morph_key' => 'model_id',
        'team_foreign_key' => 'team_id',
    ],
    'register_permission_check_method' => true,
    'teams' => false,
    'display_permission_in_exception' => false,
    'display_role_in_exception' => false,
    'enable_wildcard_permission' => false,
    'cache' => [
        'expiration_time' => \DateInterval::createFromDateString('24 hours'),
        'key' => 'spatie.permission.cache',
        'store' => 'default',
    ],
];

Upvotes: 0

Views: 5328

Answers (2)

Sam
Sam

Reputation: 997

So it turns out this was connected to another problem I was having that fortunately I was trying to fix at the same time:

Laravel upgrade broke model paths

The cause of this permissions issue was in the database but not table / field names, but actually the field contents.

In the model_has_roles table, the old App\User namespace was used (hopefully I'm using "namespace" correctly there!) and should have been App\Models\User in line with the new namespace. Then it all worked fine.

Upvotes: 1

Navneeta
Navneeta

Reputation: 58

Below few things i would like to try

$user->assignRole($this->roles)

Try echo below line just after assign

echo $user()->getRoleNames()

Also try fetch with relations

Dump($user->with('roles')->get()

It will tell you atleast roles assignment is working.

Upvotes: 1

Related Questions