我需要一个策略来在锦标赛中创建树木。
所以,在我的treeController @ store中,我有:
if (Auth::user()->cannot('generateTree', new Tree(),$tournament)) {
throw new AuthorizationException();
}
我的相应政策是:
TreePolicy.php:
public function generateTree(Tree $tree, Tournament $tournament )
{
dd($tournament);
return ($tournament->user_id == Auth::user()->id);
}
我得到了一个:
Type error: Argument 1 passed to App\Policies\TreePolicy::generateTree() must be an instance of App\Tree, instance of App\User given, called in /laravel/vendor/laravel/framework/src/Illuminate/Auth/Access/Gate.php on line 382
我缺少什么?
编辑:回应@andonovn,
我尝试过:
public function store(User $user, Tree $tree, Tournament $tournament)
{
dd($tournament);
}
并且
if (Auth::user()->cannot('generateTree', Tree::class,$tournament)) {
throw new AuthorizationException();
}
- >它给了我一个403
或者
$this->authorize('store', $tournament,Tree::class);
- >它不会进入dd();
我发现它工作的唯一方法是将策略内容放在控制器中,这不太好:
if ($tournament->user_id != Auth::user()->id){
throw new AuthorizationException();
}
编辑2:我解决了这个问题:
在控制器中:
if (Auth::user()->cannot('store', [Tree::class,$tournament])) {
throw new AuthorizationException();
}
政策
public function store(User $user, Tournament $tournament)
{
return ($tournament->user_id == $user->id);
}
答案 0 :(得分:1)
我相信generateTree()的第一个参数必须是经过身份验证的用户。尝试将其更改为public function generateTree(User $user, Tree $tree, Tournament $tournament )
编辑:
同样将can not方法更改为Auth::user()->cannot('generateTree', [Tree::class, $tournament])
(在数组中组合第2和第3个参数,看起来像Laravel总是期望2个参数,其中第2个可以是数组)