在html视图或控制器中调用角色函数

时间:2016-09-02 01:09:23

标签: php html5 laravel blade

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

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

但我不知道如何将此功能称为我的刀片视图,因为我是laravel的首发。所以任何帮助都会很棒,谢谢。再见

1 个答案:

答案 0 :(得分:2)

试试这个

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