spatie/laravel-permissions - Gate 和 hasPermissionTo 不工作

spatie/laravel-permissions - Gate and hasPermissionTo are not working

我有一个问题 spatie/laravel-permissions...

我在AuthServiceProvider.php中使用Gate来定义Superadmin(可以绕过所有权限,无需将其注册到角色)...

它与 can('the-permission') 助手完美配合。

但它不适用于 Auth::user()->hasPermissionTo('the-permission')...

.

.

下面是我的代码:

.

AuthServiceProvider.php中:

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

    Gate::before(function ($user, $ability) {
        $superadmin_rolename = 'Superadmin';
        $guard_name = 'web-admin';
        return $user->hasRole($superadmin_rolename , $guard_name ) ? true : null;
    });
}

.

.

在Blade中:

@can('add products')
    <button type="submit">Add Product</button>
@endcan

// this will work perfectly, the button will be shown

.

.

在控制器中:

public function addProduct()
{
    $admin = Auth::guard('web-admin')->user();

    if($admin->hasPermissionTo('add products')) return true;

    return false;
}

// this is not working (it return false)... i dont know why.... it should return true....

所以,正如我上面向您展示的那样:

谢谢

根据@Remul 的评论,我发现只有 can()$user->can() 可以与 Gate::before 完美配合......

那么,如果我想使用 $user->hasAnyPermission$user->hasAllPermissions 等其他方法怎么办?

.

这就是我所做的...我决定在 Admin 模型中创建一个自定义方法..

<?php

namespace Model;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class Admin extends Authenticatable
{
    use HasRoles;

    protected $guard_name = "web-admin";

    protected $fillable = ['name', 'email', 'password'];

    public function canAny(array $permissions)
    {
        foreach($permissions as $e){
            if($this->can($e)) return true;
        }

        return false;
    }

    public function canAll(array $permissions)
    {
        foreach($permissions as $e){
            if(!$this->can($e)) return false;
        }

        return true;
    }
}