【问题标题】:Problem with Laravel Policy method arguments countLaravel Policy 方法参数计数的问题
【发布时间】:2020-05-18 08:19:04
【问题描述】:

尝试授权某些NewsPolicy 时出现以下错误:

函数 App\Policies\NewsPolicy::create() 的参数太少,在第 706 行的 laravel\framework\src\Illuminate\Auth\Access\Gate.php 中传递了 1 个,而预期的正好是 2 个

我在命名空间App\Models 下有一个News 模型,在App\Policies 下有一个NewsPolicy

我的AuthServiceProvider 中还有自定义Gate::guessPolicyNamesUsing() 和下一个回调:

Gate::guessPolicyNamesUsing(function ($modelClass) {
    return ['\\App\\Policies\\' . class_basename($modelClass) . 'Policy'];
});

我发现 Laravel 出于某种原因删除了 Illuminate\Auth\Access\Gate::callPolicyMethod() 处带有 model 类名的参数:

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);
    }
}

但为什么我的政策不知道他们授权什么模型?

【问题讨论】:

    标签: php laravel laravel-6 laravel-authorization


    【解决方案1】:

    好的,问题是 viewAnycreate 方法根本不需要模型类的第二个参数。

    应该是这样的:

    public function create(User $user)
    {
        //
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多