我真的不明白发生了什么。这是我的设置和代码
在UserGroupPolicy类
中//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
中注册了此策略类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));
}
所以任何人都可以帮助我,谢谢你。
答案 0 :(得分:0)
尝试使用
$this->authorize('update',UserGroup::class);
而不是
$request->user()->can('update', UserGroup::class);
UPDATE :第二个参数必须是UserGroup类的实例,而不是UserGroup类本身。所以正确的代码是
$this->authorize('update',$objectOfUserGroupClass);//and not the class itself
有关详情,请查看here
它对我有用....