How to check same set of permissions assigned to another role?
I am using spatie permission package and I want to make sure that two roles with different names must not have same permissions while creating a role e.g
Role A
- Pemission 1
- Permission 2
- Permission 3
Role B
- Pemission 1
- Permission 2
- Permission 3
If this happens system should not create 2nd role "Role B"
@prasadchinwal5
It will check only one permission because of using diff() but I want to check array of newly assigned permissions with another array of permissions which already exists.......
$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
}
What @prasadchinwal5 suggested is good start, but just use intersect instead of diff and you are done. Then just compare counts for roleAPermissions, roleBPermissions and diff and you are done. Lot cleaner.
I want to show the name of role which have identical set of permissions
Role is in Roles table
Checking Permissions from Role_has_Permissions table so this worked in my case