我想检查用户是否是管理员。
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
中添加的答案。现在我收到错误基表或未找到视图。
答案 0 :(得分:1)
试试这个
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;
}