我陷入了一些应该简单的事情。
使用Laravel 5.3。我有User::isAdmin()
的函数设置,可以检查用户是否具有给定的角色。
我有一些条件菜单项只应为管理员显示。如何在刀片视图文件中检查角色?
我有多对多关系设置,并且对用户和角色工作正常。当我尝试auth()->user()->isAdmin()
或Auth::user()->isAdmin()
时,我收到以下错误:
调用未定义的方法Illuminate \ Auth \ GenericUser :: isAdmin()
以下是我的用户模型的副本:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Role;
class User extends Authenticatable
{
// use SoftDeletes;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'first_name', 'last_name', 'company', 'email', 'tax_id', 'address', 'city', 'state', 'zip', 'phone','password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
/**
* Find specified user role by id or name
* @param [type] $uid user_id
* @param [type] $role either name or id
* @return boolean [description]
*/
static function hasRole($uid, $role){
$user = User::find($uid);
if(is_numeric($role)){
foreach ($user->roles as $r) {
// var_dump($r->id);
if($r->id == $role){
return true;
}
return false;
}
}else{
foreach ($user->roles as $r) {
if($r->name == $role){
return true;
}
return false;
}
}
}
public function isAdmin(){
$user = User::find(Auth::user()->id);
foreach ($user->roles as $r) {
if($r->id == 1){
return true;
}
return false;
}
}
}