Reputation: 59
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()
Upvotes: 1
Views: 6065
Reputation: 1392
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();
Upvotes: 0
Reputation: 1438
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);
Upvotes: 2
Reputation: 59
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.
Upvotes: 1