Using Permissions via Roles | laravel-permission | Spatie

 SPATIE

  Laravel Permission
=====================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-permission](https://spatie.be/docs/laravel-permission/v7)  Basic-usage  Using Permissions via Roles

 Version   v7   v6   v5   v4   v3

 Other versions for crawler [v7](https://spatie.be/docs/laravel-permission/v7) [v6](https://spatie.be/docs/laravel-permission/v6) [v5](https://spatie.be/docs/laravel-permission/v5) [v4](https://spatie.be/docs/laravel-permission/v4) [v3](https://spatie.be/docs/laravel-permission/v3)

  Using Permissions via Roles
- [ Introduction ](https://spatie.be/docs/laravel-permission/v7/introduction)
- [ Support us ](https://spatie.be/docs/laravel-permission/v7/support-us)
- [ Prerequisites ](https://spatie.be/docs/laravel-permission/v7/prerequisites)
- [ Installation in Laravel ](https://spatie.be/docs/laravel-permission/v7/installation-laravel)
- [ Upgrading ](https://spatie.be/docs/laravel-permission/v7/upgrading)
- [ Questions and issues ](https://spatie.be/docs/laravel-permission/v7/questions-issues)
- [ Changelog ](https://spatie.be/docs/laravel-permission/v7/changelog)
- [ About us ](https://spatie.be/docs/laravel-permission/v7/about-us)

Basic Usage
-----------

- [ Basic Usage ](https://spatie.be/docs/laravel-permission/v7/basic-usage/basic-usage)
- [ Direct Permissions ](https://spatie.be/docs/laravel-permission/v7/basic-usage/direct-permissions)
- [ Using Permissions via Roles ](https://spatie.be/docs/laravel-permission/v7/basic-usage/role-permissions)
- [ Enums ](https://spatie.be/docs/laravel-permission/v7/basic-usage/enums)
- [ Teams permissions ](https://spatie.be/docs/laravel-permission/v7/basic-usage/teams-permissions)
- [ Wildcard permissions ](https://spatie.be/docs/laravel-permission/v7/basic-usage/wildcard-permissions)
- [ Blade directives ](https://spatie.be/docs/laravel-permission/v7/basic-usage/blade-directives)
- [ Defining a Super-Admin ](https://spatie.be/docs/laravel-permission/v7/basic-usage/super-admin)
- [ Using multiple guards ](https://spatie.be/docs/laravel-permission/v7/basic-usage/multiple-guards)
- [ Artisan Commands ](https://spatie.be/docs/laravel-permission/v7/basic-usage/artisan)
- [ Middleware ](https://spatie.be/docs/laravel-permission/v7/basic-usage/middleware)
- [ Passport Client Credentials Grant usage ](https://spatie.be/docs/laravel-permission/v7/basic-usage/passport)
- [ Example App ](https://spatie.be/docs/laravel-permission/v7/basic-usage/new-app)

Best Practices
--------------

- [ Roles vs Permissions ](https://spatie.be/docs/laravel-permission/v7/best-practices/roles-vs-permissions)
- [ Model Policies ](https://spatie.be/docs/laravel-permission/v7/best-practices/using-policies)
- [ Performance Tips ](https://spatie.be/docs/laravel-permission/v7/best-practices/performance)

Advanced usage
--------------

- [ Testing ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/testing)
- [ Database Seeding ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/seeding)
- [ Exceptions ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/exceptions)
- [ Extending ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/extending)
- [ Cache ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/cache)
- [ Events ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/events)
- [ Custom Permission Check ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/custom-permission-check)
- [ UUID/ULID ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/uuid)
- [ PhpStorm Interaction ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/phpstorm)
- [ Other ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/other)
- [ Timestamps ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/timestamps)
- [ UI Options ](https://spatie.be/docs/laravel-permission/v7/advanced-usage/ui-options)

 Using Permissions via Roles
===========================

###  On this page

1. [ Assigning Roles ](#content-assigning-roles)
2. [ Assigning Models to a Role ](#content-assigning-models-to-a-role)
3. [ Checking Roles ](#content-checking-roles)
4. [ Assigning Permissions to Roles ](#content-assigning-permissions-to-roles)
5. [ What Permissions Does A Role Have? ](#content-what-permissions-does-a-role-have)
6. [ Assigning Direct Permissions To A User ](#content-assigning-direct-permissions-to-a-user)

Assigning Roles
-----------------------------------------------------------------------------------------------------

A role can be assigned to any user:

```
$user->assignRole('writer');

// You can also assign multiple roles at once
$user->assignRole('writer', 'admin');
// or as an array
$user->assignRole(['writer', 'admin']);
```

A role can be removed from a user:

```
$user->removeRole('writer');
```

Roles can also be synced:

```
// All current roles will be removed from the user and replaced by the array given
$user->syncRoles(['writer', 'admin']);
```

Assigning Models to a Role
--------------------------------------------------------------------------------------------------------------------------------------

Sometimes it is more convenient to work from the role's side, for example when building an admin screen that lists every user with a given role. The `assignToModels`, `removeFromModels`, and `syncModels` methods on a role do the inverse of `assignRole`, `removeRole`, and `syncRoles`:

```
$role = Role::findByName('writer');

// Give the role to two users at once.
$role->assignToModels([$user1, $user2]);

// Remove it from one user.
$role->removeFromModels($user1);

// Replace every model that currently has this role with a new set.
$role->syncModels([$user2, $user3]);
```

Each method also accepts a single model, a single ID, an array of IDs, a Collection, or a mix of models and IDs:

```
$role->assignToModels($user);                  // a single model
$role->assignToModels($user->id);              // a single ID
$role->assignToModels([1, 2, 3]);              // an array of IDs
$role->assignToModels(User::query()->get());   // a Collection
$role->assignToModels([$user1, 5, $user2]);    // mixed
```

When you pass raw IDs, the package needs to know which model class they belong to. By default it uses the model registered for the role's guard (the same model `Auth::user()` returns). You can override this in two ways.

Pass the class as the second argument:

```
$role->assignToModels([1, 2, 3], User::class);
```

Or set a default once in `config/permission.php`:

```
'models' => [
    // ...
    'default_model' => App\Models\User::class,
],
```

If you need to assign the role to different model types in the same call, pass them as instances. The role can be assigned to any model that uses the `HasRoles` trait, not just users:

```
$role->assignToModels([$user, $admin, $apiClient]);
```

Checking Roles
--------------------------------------------------------------------------------------------------

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());
```

You can also determine if a user has exactly all of a given list of roles:

```
$user->hasExactRoles(Role::all());
```

The `assignRole`, `hasRole`, `hasAnyRole`, `hasAllRoles`, `hasExactRoles` and `removeRole` functions can accept a string, a `\Spatie\Permission\Models\Role` object or an `\Illuminate\Support\Collection` object.

Assigning Permissions to Roles
--------------------------------------------------------------------------------------------------------------------------------------------------

A permission can be given to a role:

```
$role->givePermissionTo('edit articles');
```

You can determine if a role has a certain permission:

```
$role->hasPermissionTo('edit articles');
```

A permission can be revoked from a role:

```
$role->revokePermissionTo('edit articles');
```

Or revoke &amp; add new permissions in one go:

```
$role->syncPermissions(['edit articles', 'delete articles']);
```

The `givePermissionTo` and `revokePermissionTo` functions can accept a string or a `Spatie\Permission\Models\Permission` object.

**NOTE: Permissions are inherited from roles automatically.**

What Permissions Does A Role Have?
------------------------------------------------------------------------------------------------------------------------------------------------------------

The `permissions` property on any given role returns a collection with all the related permission objects. This collection can respond to usual Eloquent Collection operations, such as count, sort, etc.

```
// get collection
$role->permissions;

// return only the permission names:
$role->permissions->pluck('name');

// count the number of permissions assigned to a role
count($role->permissions);
// or
$role->permissions->count();
```

Assigning Direct Permissions To A User
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Additionally, individual permissions can be assigned to the user too. For instance:

```
$role = Role::findByName('writer');
$role->givePermissionTo('edit articles');

$user->assignRole('writer');

$user->givePermissionTo('delete articles');
```

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 `true`, but `false` for `$user->hasDirectPermission('edit articles')`.

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 check if the user has a Specific or All or Any of a set of permissions directly assigned:

```
// Check if the user has Direct permission
$user->hasDirectPermission('edit articles')

// Check if the user has All direct permissions
$user->hasAllDirectPermissions(['edit articles', 'delete articles']);

// Check if the user has Any permission directly
$user->hasAnyDirectPermission(['create articles', 'delete articles']);
```

By following the previous example, when we call `$user->hasAllDirectPermissions(['edit articles', 'delete articles'])`it returns `false`, because the user does not have `edit articles` as a direct permission. When we call `$user->hasAnyDirectPermission('edit articles')`, it returns `true` because the user has one of the provided permissions.

You can examine all of these permissions:

```
// Direct permissions
$user->getDirectPermissions() // Or $user->permissions;

// Permissions inherited from the user's roles
$user->getPermissionsViaRoles();

// All permissions which apply on the user (inherited and direct)
$user->getAllPermissions();
```

All these responses are collections of `Spatie\Permission\Models\Permission` objects.

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.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
