我spatie permission package
在 Laravel 中使用,我想确保两个不同名称的角色在创建角色时不能具有相同的权限,例如
Role A
- Pemission 1
- Permission 2
- Permission 3
Role B
- Pemission 1
- Permission 2
- Permission 3
如果发生这种情况,系统不应创建第二个角色“角色 B”
谁能指导我?
我spatie permission package
在 Laravel 中使用,我想确保两个不同名称的角色在创建角色时不能具有相同的权限,例如
Role A
- Pemission 1
- Permission 2
- Permission 3
Role B
- Pemission 1
- Permission 2
- Permission 3
如果发生这种情况,系统不应创建第二个角色“角色 B”
谁能指导我?
找到解决方案感谢您的帮助
$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
}
config/permissions.php
包的配置文件()。如果没有,运行php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
Spatie\Permission\Models\Role
模型。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');
});