1

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

我使用GateinAuthServiceProvider.php来定义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;
    });
}

.

.

在刀片中:

@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....

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

  • Gate用来定义超级管理员
  • 超级管理员应授予所有访问权限
  • 它与can()和完美配合$user->can()
  • 但它不适用于$user->hasPermissionTo()<--------- 这是我想知道的

谢谢

4

1 回答 1

1

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

那么,如果我想使用另一种方法,比如$user->hasAnyPermissionor$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;
    }
}
于 2019-09-25T09:26:23.340 回答