简体   繁体   English

将当前口才传递给模型中的getXAttribute

[英]Pass Current Eloquent into getXAttribute in Model

I have create a getIsAdminAttribute that returns boolean and it works if I use Auth::user() however, now I need to pass the User object into this method so that I can check if given user is admin. 我已经创建了一个返回布尔值的getIsAdminAttribute ,如果我使用Auth::user()则可以正常工作,但是,现在我需要将User对象传递给此方法,以便我可以检查给定的用户是否为admin。

class User extends Authenticatable {

    public function getIsAdminAttribute()
    {   
       if (Admin::where('user_id', $user->id)->first()) {
          return true;
       } else {
          return false;
       }
    }
}

However, this doesn't work. 但是,这不起作用。 How can I pass the $user into this method, so that I can call it like: 如何将$user传递给此方法,以便可以这样调用它:

$user->is_admin and it returns boolean. $user->is_admin ,它返回布尔值。


If I try this, it returns null. 如果我尝试这样做,它将返回null。

getIsAdminAttribute($user) {
   dd($user);
}

You are already in the User model, so you can use $this to access the properties of the current object. 您已经在User模型中,因此可以使用$this访问当前对象的属性。

public function getIsAdminAttribute()
{   
   return Admin::where('user_id', $this->id)->count() > 0;
}

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

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