Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Aless55's avatar

Spatie roles() not working

I have a hyn/multi-tenancy application. I installed spatie/permissions package like in the documentation explained. I do not know what happend but somehow since I last cleared my cache the $user->roles does return null despite of $user->roles()->get()returning the correct collection.

Does anyone know why I cannot call $user->rolesanymore?

I am using laravel 7 and Hyn 5.6 and Spatie/permissions 3.17

@update it is funny because $user->permissions works without any problems....

0 likes
5 replies
a4ashraf's avatar

@aless55

if you read the documentation you see it only available these following function

https://spatie.be/docs/laravel-permission/v3/basic-usage/role-permissions

//You can determine if a user has a certain role:

$user->hasRole('writer');

// or at least one role from an array of roles:
$user->hasRole(['editor', 'moderator']);
//You can also determine if a user has any of a given list of roles:

$user->hasAnyRole(['writer', 'reader']);
// or
$user->hasAnyRole('writer', 'reader');
//You can also determine if a user has all of a given list of roles:

$user->hasAllRoles(Role::all());

there is no option to get user role like this $user->role();

Aless55's avatar

@a4ashraf of course you can, why should the package itself use it then? The HasRoles Trait which you have to use in your model includes the roles() relationship to retrieve all roles of an user. My problem is, that I cannot access it with eloquents magic method, although it should work.

NeuronySolutions's avatar

If $user->roles()->get() works and $user->roles doesn't work, it means the roles are cached.

Try running php artisan optimize:clear and see if it works.

Aless55's avatar

@NeuronySolutions Thanks for your answer, if my memory serves me correctly, the problem was a wrongly applied cast. But oh man, it took a while to find that out ( I don't even know why I put it there in the first place^^)

Please or to participate in this conversation.