Laravel 政策授权问题

Problems with Laravel Policies Authorization

我真的不明白发生了什么事。这是我的设置和代码

在用户组策略中class

//Here I want to check that if $user model have group_id <= 4 
//so they cannot change group_id when editing other users

public function update(User $user, UserGroup $userGroup)
{
    return $user->group->id <= 4;
}

我在 AuthService Provider

中注册了此政策 class
protected $policies = [
    'App\User' => 'App\Policies\UserPolicy',
    'App\UserGroup' => 'App\Policies\UserGroupPolicy',
    'App\Team' => 'App\Policies\TeamPolicy',
    'App\Branch' => 'App\Policies\BranchPolicy',
    'App\Company' => 'App\Policies\CompanyPolicy',
];

但是在测试的时候出现了很多错误

在控制器中

//For testing
public function index(Request $request)
{
    //If I do not pass the user instance, like Laravel official document
    //It will throw: : Too few arguments to function
    //App\Policies\UserGroupPolicy::update(), 1 passed in 
    //path\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php
    //on line 481 and exactly 2 expected

    var_dump($request->user()->can('update', UserGroup::class));

    //if I pass, it will always return true although I edit the update function
    //in UserGroupPolicy class just return false
    var_dump($request->user()->can('update', $request->user(), UserGroup::class));

}

所以谁能帮帮我,谢谢。

尝试使用

$this->authorize('update',UserGroup::class);

而不是

$request->user()->can('update', UserGroup::class);

UPDATE:第二个参数必须是 UserGroup class 的实例而不是 UserGroup class itself.So 正确的代码是

 $this->authorize('update',$objectOfUserGroupClass);//and not the class itself

更多信息请查看here

对我有用....