Laravel中Gate适合简单闭包授权,Policy面向模型组织复杂规则;均通过can/@can/authorize等调用,需在AuthServiceProvider注册;Gate用Gate::define定义能力,Policy需生成类并映射到模型。

在 Laravel 中,Gate 和 Policy 是实现细粒度权限控制的核心机制。Gate 适合简单、闭包式的授权逻辑;Policy 更适合围绕某个模型组织复杂、可复用的授权规则。两者都配合 can、@can、authorize 等方法使用,且自动集成到中间件和控制器中。
Gate 用于定义基于能力(ability)的授权规则,通常写在 App\Providers\AuthServiceProvider 的 boot 方法里。它不绑定具体模型类,但可以接收模型实例作为参数。
Gate::define 注册一个能力名(如 'delete-post'),回调函数返回布尔值$user),后续参数是资源(如 $post)before 设置全局前置检查(如管理员绕过)示例:
Gate::define('delete-post', function ($user, $post) {Policy 是与特定模型强关联的授权类,推荐为每个需要权限控制的模型单独创建。Laravel 提供了生成命令:php artisan make:policy PostPolicy --model=Post。
view、create、update、delete 等常用方法,也可自定义(如 publish)function (User $user, Post $post),返回布尔值AuthServiceProvider@policies 数组中注册模型与 Policy 的映射关系示例注册:
protected $policies = [授权检查可在多处触发,方式灵活且语义清晰:
$this->authorize('update', $post)(抛异常)或 $this->authorizeForUser($user, 'update', $post)
@can('delete', $post) ... @endcan 或 @cannot('view', $post) ... @endcannot
authorize() 方法里调用 $this->user()->can('create', Post::class)
auth()->user()->can('publish', $post) 或 Gate::allows('publish-post', $post)
实际项目中常需结合场景做优化:
update(User $user, Post $post, string $field)),增强灵活性Post::class)而非实例,便于判断是否允许新建can 默认返回 false,无需手动判空;但 Gate 回调中的 $user 可能为 null,需自行处理基本上就这些。用好 Gate 和 Policy,能让权限逻辑清晰分离、易于测试和维护。
以上就是Laravel如何使用Gate和Policy进行授权?(权限控制)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号