1

I am trying to get it by same way i am getting the list of users with a certain Permission, but with role it's not working throwing me

Call to undefined method Spatie\Permission\Models\Role::roles()

The way i get list of users with a certain role:

$permission = $request->permission;
$usersWithPerms = User::permission($permission)->get(); 
return array("usersWithPerms"=>$usersWithPerms);

The way im trying to get roles with a certain permission:

  $groupsWithPerms = Role::permission('perms_givePermToRole')->get(); 
  return array("groupsWithPerms"=>$groupsWithPerms);

BadMethodCallException Call to undefined method Spatie\Permission\Models\Role::roles()

apokryfos
  • 38,771
  • 9
  • 70
  • 114
Ascerx
  • 59
  • 1
  • 9
  • i think your question is wrong because every role has many permissions not the opposite – Ahmad Elkenany Dec 25 '18 at 13:14
  • no, it's not wrong, cause there are many roles with same perm, so i want a list of roles that have assigned some perm. But i got it work. Ty – Ascerx Dec 25 '18 at 19:49

3 Answers3

2

get the permissions of a role and get the roles of a permission

$permission = Permission::findOrFail(1);
$groupsWithPerms = $permission->getRoleNames();
//dd($groupsWithPerms);

$role = Role::findOrFail(1);
$groupsWithRoles = $role->getPermissionNames();
//dd($groupsWithRoles);
ztvmark
  • 1,319
  • 15
  • 11
1

The only thing i get its a name but not id of the roles with a certain permission:

$permission = Permission::findOrFail($request->idPermission);
$groupsWithPerms = $permission->getRoleNames();

Where: getRoleNames() is a method from spatie package. So this works fine but you only get the names of the roles not ids.

Ascerx
  • 59
  • 1
  • 9
0

There is no in-built shortcut to get them in the package, but querying for them is simple enough:

//Eager load roles to get all data in just 1 query
$permission = Permission::with('roles')
    ->where('name', 'perms_givePermToRole')
    ->first();
$rolesWithPerm = $permission->roles;

//or

$rolesWithPerm = Role::whereHas('permissions', function($permissions){
   $permissions->where('name', 'perms_givePermToRole');
})->get();
Augusto Moura
  • 1,224
  • 7
  • 17