laravel - 对 Laravel Controller 策略中的 $this->authori

public function update(Request $request, Post $post)
{
    $this->authorize('update', $post);

}

根据我的理解,第二个参数告诉 Laravel 哪个模型是关于“更新”权限的。在本例中,$post (App\Models\Post) 模型。让我感到困惑的部分是,第二个 authorize() 是否仅作为对模型的引用存在,或者是否确实传递了实际模型的实例,即使“更新”方法不需要它?

不需要实际 $post 实例的更新策略示例:

public function update(User $user)
    {
        return $user->hasPermissionTo('update posts');
    }

需要 $post 实例的更新策略示例:

public function update(User $user, Post $post)
        {
            return $post->user_id === $user->id;
        }

$this->authorize('update', $post) 是否适用于这两个示例,即使在一种情况下更新方法只需要一个参数而在另一种情况下它需要两个参数?如果需要三个呢?

最佳答案

您正在编写策略方法,因此您可以确定它需要哪些参数。在您的示例中,您正在调用 $this->authorize('update', $post) 因此您的策略方法需要有一个 $post 参数来表示对象已更新。

显然,如果您不将其作为参数传递,则它没有任何可授权的内容。没有模型参数的策略方法适用于没有模型可授权的情况,例如创建函数。

来自 the documentation :

Some policy methods only receive an instance of the currently authenticated user. This situation is most common when authorizing create actions. For example, if you are creating a blog, you may wish to determine if a user is authorized to create any posts at all. In these situations, your policy method should only expect to receive a user instance.

关于laravel - 对 Laravel Controller 策略中的 $this->authorize() 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72366634/

相关文章:

docker-compose - 如何获取分离容器的 docker-compose exec 的控制

css - 使用 FontAwesome 网络字体时的 CSP 警告(工具包)

ios - Firebase Messaging 不会在 iOS (11.4.1) 上调用 Back

aws-lambda - 让 Alexa 通过自定义技能通过从后端调用任何 API 而不说 'Ale

javascript - React.useEffect 在依赖项发生变化时不会触发

database - 如何使用 LevelDB 访问 GoEthereum Transaction

javascript - 当我尝试从 react 查询中破坏数据时,我得到属性 'data' 在类型

python - 如何在 Starlette/FastAPI 中修改 Request 对象的范围字段

r - 无法在 MacOS M1 Monterey 上安装 stringi R 包

c - 使用 C 编辑文件