Gandalf
Gandalf

Reputation: 13693

Adding and revoking permission to a specific user with a specific role

I am using this package https://github.com/spatie/laravel-permission for roles and permissions. In my application i have several roles like:

  1. Users
  2. Employers
  3. Shop owners
  4. Vendors

Depending on the level of trust i want each person in a specific role to have access to specific permissions only. For a user of role user with id 7 i want him or her to have permissions editor,'shopping` and no other permission.

Another user of id 65 in the same role user can have editor,'shopping,'edit profile,'view maps' permissions.

When i look at the docs https://docs.spatie.be/laravel-permission/v3/basic-usage/role-permissions/

can a user in a specific role be given a permission different from another user in the same role?

Upvotes: 2

Views: 6793

Answers (3)

RobyB
RobyB

Reputation: 1436

To remove a role, and not the Permissions, you can execute:

User::find(1)->removeRole('admin');

We are removing (revoking) the role 'admin' to the user with id 1.

This is done using the interactive shell with tinker. To enter in Tinker execute:

php artisan tinker

Then you can find and modify entities:

enter image description here

In fact we can see here that the user has no more the role 'admin';

But still the role 'user', that is the basic.

enter image description here

Upvotes: 0

Kamlesh Paul
Kamlesh Paul

Reputation: 12391

like this.?

specific user role and permission you can manage

$user = User::find(7);

$user->assignRole("user"); // assign role to that user

$user->givePermissionTo(['editor','shopping']); // for giving permission to user

$user->revokePermissionTo(['editor','shopping']); // for revoke permission to user

$user = User::find(65);

$user->assignRole("user"); // assign role to that user

$user->givePermissionTo(['editor','shopping','edit profile']); // for giving permission to user

$user->revokePermissionTo(['editor','shopping','edit profile']); // for revoke permission to user

Upvotes: 6

Remul
Remul

Reputation: 8252

You can use Direct Permissions for this.

From the docs:

A permission can be given to any user:

$user->givePermissionTo('edit articles');

// You can also give multiple permission at once
$user->givePermissionTo('edit articles', 'delete articles');

// You may also pass an array
$user->givePermissionTo(['edit articles', 'delete articles']);

A permission can be revoked from a user:

$user->revokePermissionTo('edit articles');

//Or revoke & add new permissions in one go:    
$user->syncPermissions(['edit articles', 'delete articles']);

In your case:

// assign the role to the user
$user->assignRole('user');

// assign the permissions to the user
$user->givePermissionTo(['editor', 'shopping', 'edit profile', 'view maps']);

Upvotes: 2

Related Questions