Laravel-permission: Get all Permissions associated to a Role

Created on 19 Oct 2017  路  4Comments  路  Source: spatie/laravel-permission

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

Most helpful comment

You might save another query by using the relationship:

Role::findByName('writer')->permissions returns a collection.

All 4 comments

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();
    }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

feliperoan picture feliperoan  路  3Comments

bhulsman picture bhulsman  路  3Comments

younus93 picture younus93  路  4Comments

wreighsantos picture wreighsantos  路  4Comments

ergonomicus picture ergonomicus  路  3Comments