-2

I am using spatie permission package in Laravel 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"

Can anyone please guide me?

apokryfos
  • 38,771
  • 9
  • 70
  • 114

2 Answers2

0
  1. Make sure you’ve published the configuration file(config/permissions.php) of the package. If not, run

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

  1. Extend the Spatie\Permission\Models\Role model.
  2. Change the configuration file to point the extended role model instead of the default one.
  3. Override the static boot method inside the extended model and add this callback:
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. You can catch this exception later in the controller and return the error message as a response if you want to let the user know what happened.
Elnur Hajiyev
  • 464
  • 1
  • 4
  • 14
0

Found Solution thank you for helping

 $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
    }