Laravel 策略方法参数计数有问题
Problem with Laravel Policy method arguments count
尝试授权某些 NewsPolicy
:
时出现以下错误
Too few arguments to function App\Policies\NewsPolicy::create(), 1 passed in laravel\framework\src\Illuminate\Auth\Access\Gate.php on line 706 and exactly 2 expected
我在命名空间 App\Models
下有一个 News
模型,在 App\Policies
.
下有一个 NewsPolicy
我的 AuthServiceProvider
中还有自定义 Gate::guessPolicyNamesUsing()
和下一个回调:
Gate::guessPolicyNamesUsing(function ($modelClass) {
return ['\App\Policies\' . class_basename($modelClass) . 'Policy'];
});
我发现 Laravel 出于某种原因删除了带有 model class 名称的参数Illuminate\Auth\Access\Gate::callPolicyMethod()
:
protected function callPolicyMethod($policy, $method, $user, array $arguments)
{
// If this first argument is a string, that means they are passing a class name
// to the policy. We will remove the first argument from this argument array
// because this policy already knows what type of models it can authorize.
if (isset($arguments[0]) && is_string($arguments[0])) {
array_shift($arguments);
}
if (! is_callable([$policy, $method])) {
return;
}
if ($this->canBeCalledWithUser($user, $policy, $method)) {
return $policy->{$method}($user, ...$arguments);
}
}
但为什么我的政策不知道他们授权的型号?
好的,问题是 viewAny
和 create
方法根本不需要模型 class 的第二个参数。
它应该是这样的:
public function create(User $user)
{
//
}
尝试授权某些 NewsPolicy
:
Too few arguments to function App\Policies\NewsPolicy::create(), 1 passed in laravel\framework\src\Illuminate\Auth\Access\Gate.php on line 706 and exactly 2 expected
我在命名空间 App\Models
下有一个 News
模型,在 App\Policies
.
NewsPolicy
我的 AuthServiceProvider
中还有自定义 Gate::guessPolicyNamesUsing()
和下一个回调:
Gate::guessPolicyNamesUsing(function ($modelClass) {
return ['\App\Policies\' . class_basename($modelClass) . 'Policy'];
});
我发现 Laravel 出于某种原因删除了带有 model class 名称的参数Illuminate\Auth\Access\Gate::callPolicyMethod()
:
protected function callPolicyMethod($policy, $method, $user, array $arguments)
{
// If this first argument is a string, that means they are passing a class name
// to the policy. We will remove the first argument from this argument array
// because this policy already knows what type of models it can authorize.
if (isset($arguments[0]) && is_string($arguments[0])) {
array_shift($arguments);
}
if (! is_callable([$policy, $method])) {
return;
}
if ($this->canBeCalledWithUser($user, $policy, $method)) {
return $policy->{$method}($user, ...$arguments);
}
}
但为什么我的政策不知道他们授权的型号?
好的,问题是 viewAny
和 create
方法根本不需要模型 class 的第二个参数。
它应该是这样的:
public function create(User $user)
{
//
}