Laravel Eloquent - pluck() 角色名称

Laravel Eloquent - pluck() role name

我正在尝试从具有角色的请求中获取经过身份验证的用户对象。我正在使用 Spatie laravel-permissions 和 Laravel 8.

像这样从请求中获取用户对象

$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"
         }
      }
   ]
}

我需要退回的东西

{
   "id":1,
   "name":"User name",
   "email":"User email",
   "email_verified_at":null,
   "company":"--",
   "phone":"--",
   "created_at":"--",
   "updated_at":"--",
   "roles":["Super Admin"]
}

已将 roles 添加到用户对象,就像这样

$user = $request->user();
$user->roles = $user->roles()->pluck('name');
return $user;

另一种选择是使用 hiddenappends 和访问器,例如 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
}

return $request->user(); 一起执行此操作将自动使 roles 不可见,并附加 role_names。在您的代码中,您应该得到输出:

{
   "id":1,
   "name":"User name",
   "email":"User email",
   "email_verified_at":null,
   "company":"--",
   "phone":"--",
   "created_at":"--",
   "updated_at":"--",
   "role_names":["Super Admin"]
}

您也可以这样做:

$user->roles = User::find($user->id)->getRoleNames();