检查用户是否在laravel中为admin


Check if user is admin in laravel

我想检查用户是否是admin。

User table

id | role_id | name
1  | 3       | test

Role table

id | role     
1  | user     
2  | employee 
3  | admin    

User model

class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
    'name', 'email', 'gender', 'password',
];
protected $hidden = [
    'password', 'remember_token',
];
public function roles()
{
    return $this->belongsToMany('App'Role');
}
public function isAdmin() {
   return $this->roles()->where('role', 'user')->exists();
}

}

Role model

class Role extends Model
{
 //
}

Blade template

 @if(Auth::user()->isAdmin())
     user is admin
 @endif

我找不到我必须在function isAdmin中添加的答案。现在我得到错误的基本表或视图未找到

试试这个

class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
    'name', 'email', 'gender', 'password',
];
protected $hidden = [
    'password', 'remember_token',
];
public function role()
{
    return $this->belongsTo('App'Role');
}
public function isAdmin() {
   if($this->role->name == 'admin'){
        return true;
    }
    return false;
}