从 html 视图或控制器中的模型调用角色函数

Call roles function from model in html view or controller

我已经有一个可以正常使用的自定义身份验证。但我只能在我的路线中使用它来阻止或释放访问权限。但现在我想隐藏或显示某些角色和用户的按钮和链接,例如:

@if(user==admin) // this line (Auth::user->roles()) ??
<a href="admin">Configuration</a
@endif

但遗憾的是,无论我如何尝试,我都做不到。就像我说的,我已经有了这个用户模型

public function roles()
{
    return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}

public function hasAnyRole($roles)
{
    if (is_array($roles)) {
        foreach ($roles as $role) {
            if ($this->hasRole($role)) {
                return true;
            }
        }
    } else {
        if ($this->hasRole($roles)) {
            return true;
        }
    }
    return false;
}

public function hasRole($role)
{
    if ($this->roles()->where('name', $role)->first()) {
        return true;
    }
    return false;
}

但我不知道如何将此函数调用到我的 blade 视图,因为我是 laravel 的初学者。所以任何帮助都会很棒,谢谢。再见

试试这个

@if(\Auth::check() && \Auth::user()->hasRole('admin')) 
<a href="admin">Configuration</a
@endif