-
Notifications
You must be signed in to change notification settings - Fork 330
Checking roles and abilities
Note: Generally speaking, you should not have a need to check roles directly. It is better to allow a role certain abilities, then check for those abilities instead. If what you need is very general, you can create very broad abilities. For example, an
access-dashboard
ability is always better than checking foradmin
oreditor
roles directly. For the rare occasion that you do want to check a role, that functionality is available here.
The bouncer can check if a user has a specific role:
Bouncer::is($user)->a('moderator');
If the role you're checking starts with a vowel, you might want to use the an
alias method:
Bouncer::is($user)->an('admin');
For the inverse, you can also check if a user doesn't have a specific role:
Bouncer::is($user)->notA('moderator');
Bouncer::is($user)->notAn('admin');
You can check if a user has one of many roles:
Bouncer::is($user)->a('moderator', 'editor');
You can also check if the user has all of the given roles:
Bouncer::is($user)->all('editor', 'moderator');
You can also check if a user has none of the given roles:
Bouncer::is($user)->notAn('editor', 'moderator');
These checks can also be done directly on the user:
$user->is('admin');
$user->isNot('admin');
$user->isAll('editor', 'moderator');
You can get all abilities for a user directly from the user model:
$abilities = $user->getAbilities();
This will return a collection of the user's abilities, including any abilities granted to the user through their roles.
Authorizing users is handled directly at Laravel's Gate
, or on the user model ($user->can($ability)
).
For convenience, the bouncer class provides two passthrough methods:
Bouncer::can($ability);
Bouncer::cannot($ability);
These call directly into the Gate
class.