I'm trying to get the authenticated user object from the request with roles. I'm using Spatie laravel-permissions and Laravel 8.
Getting User object from request like so
$request->user()->getRoleNames()->pluck('name');
return $request->user();
Returns
{
"id":1,
"name":"User name",
"email":"User email",
"email_verified_at":null,
"company":"--",
"phone":"--",
"created_at":"--",
"updated_at":"--",
"roles":[
{
"id":1,
"name":"Super Admin",
"guard_name":"web",
"created_at":"--",
"updated_at":"--",
"pivot":{
"model_id":1,
"role_id":1,
"model_type":"App\\Models\\User"
}
}
]
}
What I need to be returned
{
"id":1,
"name":"User name",
"email":"User email",
"email_verified_at":null,
"company":"--",
"phone":"--",
"created_at":"--",
"updated_at":"--",
"roles":["Super Admin"]
}
Another alternative is using hidden
, appends
and an accessor, like getRoleNamesAttribute()
:
class User extends Model {
...
// This will hide `roles` from your `User`, when converted to JSON/Array/etc
protected $hidden = ['roles'];
// This will add `role_names` to your `User`, when converted to JSON/Array/etc
protected $appends = ['role_names'];
// Accessible via `$user->role_names`, or `user.role_names` in JSON
public function getRoleNamesAttribute() {
return $this->roles->pluck('name');
}
... // Everything else
}
Doing this, in conjunction with return $request->user();
will automatically make roles
invisible, and appends role_names
. In your code, you should get the output:
{
"id":1,
"name":"User name",
"email":"User email",
"email_verified_at":null,
"company":"--",
"phone":"--",
"created_at":"--",
"updated_at":"--",
"role_names":["Super Admin"]
}
Added roles
to user object, like so
$user = $request->user();
$user->roles = $user->roles()->pluck('name');
return $user;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With