Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent - pluck() role name

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"]
}
like image 205
Josh Bonnick Avatar asked Oct 16 '25 20:10

Josh Bonnick


2 Answers

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"]
}
like image 91
Tim Lewis Avatar answered Oct 18 '25 09:10

Tim Lewis


Added roles to user object, like so

$user = $request->user();
$user->roles = $user->roles()->pluck('name');
return $user;
like image 31
Josh Bonnick Avatar answered Oct 18 '25 11:10

Josh Bonnick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!