简体   繁体   English

Laravel Eloquent - pluck() 角色名称

[英]Laravel Eloquent - pluck() role name

I'm trying to get the authenticated user object from the request with roles.我正在尝试从具有角色的请求中获取经过身份验证的用户对象。 I'm using Spatie and Laravel 8.我正在使用Spatie和 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"]
}

Note:笔记:

I don't understand why adding $request->user()->getRoleNames()->pluck('name');我不明白为什么要添加$request->user()->getRoleNames()->pluck('name'); makes the roles appear.使角色出现。 Without it, the roles don't appear at all.没有它,角色根本不会出现。 I assumed I would need to do $request->user()->with('roles');我以为我需要做$request->user()->with('roles'); but that doesn't work (returns null ).但这不起作用(返回null )。

False alarm.虚惊。 Think I was just overthinking it.以为我只是多虑了。

Added roles to user object, like so向用户对象添加了roles ,就像这样

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

Another alternative is using hidden , appends and an accessor, like getRoleNamesAttribute() :另一种替代方法是使用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
}

Doing this, in conjunction with return $request->user();这样做,结合return $request->user(); will automatically make roles invisible, and appends role_names .将自动使roles不可见,并附加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"]
}

你也可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM