I have a route to show all permissions assigned to a role. I'm currently getting the role by name. I would like to get the permissions assigned to that role, like so:
public function show(Role $role, $role_name)
{
try {
if ($role = $role->findByName($role_name)) {
//$role has value as expected
$permissions = $role->getAllPermissions(); //trying to get permissions here throws error
return $this->response->array(compact('role', 'permissions'));
//$role->with('permissions') doesn't have the desired result either.
}
} catch (Exception $e) {
throw new NotFoundHttpException('Role not found');
}
}
I guess this is related to #448
Never mind, I solved this.
public function show(Role $role, $role_name)
{
try {
if ($role = $role->findByName($role_name)) {
$permissions = $role->permissions()->get();
return $this->response->array(compact('role', 'permissions'));
}
} catch (Exception $e) {
throw new NotFoundHttpException('Role not found');
}
}
You might save another query by using the relationship:
Role::findByName('writer')->permissions returns a collection.
Or, if you want to alternatively get all roles assigned to permission, use Eloquent:
Permission::whereName('writer')->first()->roles
Then, you can manipulate easier with extra functions such as Pluck :)
Permission::whereName('writer')->first()->roles->pluck('name)
for those who want all permissions associated with user roles
protected $appends = ['permissions'];
public function getPermissionsAttribute()
{
return $this->roles->map(function ($role) {
return $role->permissions;
})->collapse()->pluck('name')->unique();
}
Most helpful comment
You might save another query by using the relationship:
Role::findByName('writer')->permissionsreturns a collection.