Get user roles and its permissions #2187
Answered
by
erikn69
lucianobosco
asked this question in
Q&A
-
I need to return all roles with permissions for an authenticated user. The expected response is: 'roles': [
"editor":[
"post.create",
"post.edit",
"post.delete",
"post.restore",
...
],
"contributor":[
"post.create",
"post.edit",
...
]
] I'm using Api Resources to get user info and this is what I have so far. As you can see, <?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserInfoResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->profile->full_name,
'email' => $this->email,
'roles' => $this->roles->pluck('name'),
'permissions' => $this->getPermissionsViaRoles()->pluck('name')
];
}
} Please note that a user could have more than 1 role. |
Beta Was this translation helpful? Give feedback.
Answered by
erikn69
Sep 27, 2022
Replies: 1 comment 1 reply
-
Maybe try $this->load('roles.permissions');
///
'roles' => $this->roles->keyBy('name')->map(fn($role) => $role->permissions->pluck('name'))->toArray(), |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
lucianobosco
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe try