I have following error when trying to authorize some 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
I have a News
model under the namespace App\Models
and a NewsPolicy
under App\Policies
.
Also I have custom Gate::guessPolicyNamesUsing()
in my AuthServiceProvider
with next callback:
Gate::guessPolicyNamesUsing(function ($modelClass) {
return ['\\App\\Policies\\' . class_basename($modelClass) . 'Policy'];
});
I find out that Laravel for some reason removing the argument with the model class name at 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);
}
}
But why my policy don't know what model they authorize?
Okay, the problem is viewAny
and create
methods simply does not need second argument with model class.
It should look like this:
public function create(User $user)
{
//
}