【问题标题】:Laravel 5.8 isAdmin Gate?Laravel 5.8 是管理门?
【发布时间】:2019-12-20 19:26:17
【问题描述】:

我正在学习如何使用 Gate 和 @can 的东西

在我的 AuthServiceProvider 我有

public function boot()
{
    $this->registerPolicies();
    $this->registerPostPolicies();
}

public function registerPostPolicies()
{
    Gate::define('isAdmin', function($user) {
        return $user->roles->where('title', 'like', '%' . 'Admin')->count();
    });
}

在我的刀片中,我有

...
            @can('isAdmin')
                <a aria-disabled="false" href="{{ route('admin.home')}}" target="_self" class="dropdown-item" role="menuitem" ><i class="fa fa-upload"></i> Admin Menu</a>  
            @endcan 
...

对于我拥有的角色

| id | title       | 
+----+-------------+-
|  1 | Admin       | 
|  2 | User        | 
|  3 | Group Admin | 
|  4 | Site Admin  | 
+----+-------------+-

这就是为什么喜欢 %Admin 查询...

但我发现门似乎不起作用..它只是阻止了所有人..我想为角色标题中包含管理员的任何人启用管理员菜单..

有什么建议吗?

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-blade


    【解决方案1】:

    您应该使用带括号的$user-&gt;roles() 来表示您正在从数据库中查询。

    return $user->roles()->where('title', 'like', '%' . 'Admin')->count();
    

    没有(),它就变成了Collection,过滤集合时不能用LIKE和where()。参考Collections - Laravel Docs

    【讨论】:

    • 它总是小事.... - 尽管应该将返回值设为布尔值吗?或者可以是一个数字== true,error == false?
    • 如果您想保持简单,则不需要。 0 总是意味着错误。其他数字表示正确。
    猜你喜欢
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2021-03-18
    • 2019-10-20
    • 1970-01-01
    • 2020-01-04
    • 2020-03-12
    相关资源
    最近更新 更多