A role can be assigned to any user:
// You can also assign multiple roles at once
// or as an array
A role can be removed from a user:
Roles can also be synced:
// All current roles will be removed from the user and replaced by the array given
You can determine if a user has a certain role:
You can also determine if a user has any of a given list of roles:
You can also determine if a user has all of a given list of roles:
removeRole functions can accept a
\Spatie\Permission\Models\Role object or an
A permission can be given to a role:
You can determine if a role has a certain permission:
A permission can be revoked from a role:
revokePermissionTo functions can accept a
string or a
Permissions are inherited from roles automatically.
Additionally, individual permissions can be assigned to the user too.
$role = Role::findByName('writer');
In the above example, a role is given permission to edit articles and this role is assigned to a user.
Now the user can edit articles and additionally delete articles. The permission of 'delete articles' is the user's direct permission because it is assigned directly to them.
When we call
$user->hasDirectPermission('delete articles') it returns
This method is useful if one builds a form for setting permissions for roles and users in an application and wants to restrict or change inherited permissions of roles of the user, i.e. allowing to change only direct permissions of the user.
You can list all of these permissions:
// Direct permissions
$user->getDirectPermissions() // Or $user->permissions;
// Permissions inherited from the user's roles
// All permissions which apply on the user (inherited and direct)
All these responses are collections of
If we follow the previous example, the first response will be a collection with the
delete article permission and
the second will be a collection with the
edit article permission and the third will contain both.
##NOTE about using permission names in policies
authorize() for a policy method, if you have a permission named the same as one of those policy methods, your permission "name" will take precedence and not fire the policy. For this reason it may be wise to avoid naming your permissions the same as the methods in your policy. While you can define your own method names, you can read more about the defaults Laravel offers in Laravel's documentation at https://laravel.com/docs/5.8/authorization#writing-policies