简体   繁体   English

检查用户是否为laravel管理员

[英]Check if user is admin in laravel

I want to check if the user is admin or not. 我想检查用户是否是管理员。

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

I cant find the answer what I have to add in the function isAdmin nothing works. 我无法找到答案,我必须在function isAdmin添加什么function isAdmin Now i get the error Base table or view not found. 现在我得到错误基表或未找到视图。

Try this 尝试这个

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;
}

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

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