-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?

1
  • What code are you currently using? Commented Jan 13, 2020 at 22:47

2 Answers 2

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.
1
  • Thank you for helping, I've found the solution :) Commented Jan 14, 2020 at 21:23
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
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.