向具有特定角色的特定用户添加和撤消权限

时间:2020-01-29 11:57:45

标签: laravel laravel-permission

我正在使用此软件包https://github.com/spatie/laravel-permission获取角色和权限。在我的应用程序中,我有几个角色,例如:

  1. 用户
  2. 雇主
  3. 商店老板
  4. 供应商

根据信任级别,我希望具有特定角色的每个人只能访问特定权限。对于ID为for x,y,z in my_tuple: ''' Rest of the code goes here -- it can loop over each element of the list of tuples And unpack each element of the tuple in the form of x,y,z ''' 且角色为user的用户,我希望他或她拥有权限7,“购物”且没有其他权限。

另一个ID为editor且具有65角色的用户可以拥有user,“购物editor”,“查看地图”的权限。

当我看文档https://docs.spatie.be/laravel-permission/v3/basic-usage/role-permissions/

可以为处于特定角色的用户授予与具有相同角色的另一个用户不同的权限吗?

2 个答案:

答案 0 :(得分:3)

像这样。

您可以管理的特定用户角色和权限

$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

答案 1 :(得分:1)

您可以为此使用Direct Permissions

从文档中

可以将权限授予任何用户:

$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']);

可以撤消用户的权限:

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

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

在您的情况下:

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

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