-2

spatie permission package在 Laravel 中使用,我想确保两个不同名称的角色在创建角色时不能具有相同的权限,例如

Role A
 - Pemission 1
 - Permission 2
 - Permission 3

Role B
 - Pemission 1
 - Permission 2
 - Permission 3

如果发生这种情况,系统不应创建第二个角色“角色 B”

谁能指导我?

4

2 回答 2

0

找到解决方案感谢您的帮助

 $roles = Role::get();
        $permissions = $request->input('permissions');
        $notSame = false;
        $sameRole = null;
        for ($i = 0; $i < count($roles); $i++) {
            $role_permissions[$i] = $roles[$i]->getAllPermissions()
                ->pluck('id')->toArray();
            for ($j = 0; $j < count($role_permissions[$i]); $j++) {
                if ($role_permissions[$i] == $permissions) {
                    $notSame = true;
                    $sameRole = $roles[$i];
                    break;
                }
            }
        }
        /**
         * Below condition will check if same set of permissions is
         * not assigned to any other role then It will be processed
         * further otherwise user have to choose different set of
         * permission
         *
         */
        if ($notSame && ($sameRole != null)) {
            alert()->warning('Role Already Exists', 'A role named as "' . $sameRole->name . '" with same permissions 
             already exists try with another permissions set');
         return redirect()->back();

        } else {

    - Write here your code to store into DB
    }
于 2020-01-14T21:22:19.657 回答
0
  1. 确保你已经发布了config/permissions.php包的配置文件()。如果没有,运行

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

  1. 扩展Spatie\Permission\Models\Role模型。
  2. 更改配置文件以指向扩展角色模型而不是默认角色模型。
  3. 覆盖boot扩展模型中的静态方法并添加此回调:
self::creatig(function($model) {
    $permissions = $model->permissions;
    $existingRoles = Role::whereHas('permissions', function($query) using $permissions {
        $query->whereIn('id', $permissions->pluck('id'));
    })->get();
    if (!$existingPosts->isEmpty()) throw Exception('There is already a role with these permissions');
});
  1. 如果您想让用户知道发生了什么,您可以稍后在控制器中捕获此异常并返回错误消息作为响应。
于 2020-01-13T22:58:35.823 回答