Authorize 属性
#[Authorize] 属性将 Laravel 的 Gate 系统直接集成到 Livewire 操作中。它确保只有在用户具备必要权限时才执行操作,否则抛出 403 Forbidden 响应。
基本用法
将 #[Authorize] 属性应用到任意操作方法。传入能力名称与可选参数:
php
<?php // resources/views/components/post/⚡edit.blade.php
use Livewire\Attributes\Authorize;
use Livewire\Component;
use App\Models\Post;
new class extends Component {
public Post $post;
#[Authorize('update', 'post')] // [tl! highlight]
public function save()
{
$this->post->save();
}
};blade
<button wire:click="save">
Update Post
</button>调用 save() 时,Livewire 会自动检查当前用户是否有权对组件上存储的 $post 模型执行 update。
参数解析
该属性按以下顺序解析要授权的对象:
- 无参数 — 检查不需要模型的简单 Gate(例如
#[Authorize('view-dashboard')])。 - 类名字符串 — 适用于尚无实例的
create权限(例如#[Authorize('create', Post::class)])。 - 方法参数 — 从方法自身的参数中解析。
- 组件属性 — 在组件上查找与参数名匹配的属性(例如
public Post $post)。
从方法参数解析
基于方法参数进行授权时,必须为参数添加类型提示,以便 Livewire 知道要解析哪个模型:
php
<?php // resources/views/components/⚡comment-manager.blade.php
use Livewire\Attributes\Authorize;
use Livewire\Component;
use App\Models\Comment;
new class extends Component {
#[Authorize('delete', 'comment')] // [tl! highlight]
public function deleteComment(Comment $comment) // [tl! highlight]
{
$comment->delete();
}
};::: important
若通过方法参数解析模型,则必须提供类型提示(例如 Comment $comment)。否则 Livewire 无法确定要解析哪个模型,授权检查将失败。
附加上下文
使用策略授权操作时,可以将数组作为第二个参数传入。数组的第一个元素用于确定应调用哪个策略,其余元素作为参数传给策略方法。
php
<?php
use Livewire\Attributes\Authorize;
use Livewire\Component;
use App\Models\Comment;
use App\Models\Post;
new class extends Component {
public Post $post;
#[Authorize('create', [Comment::class, 'post'])] // [tl! highlight]
public function createComment()
{
$this->post->comments()->create([
'body' => 'New comment'
]);
}
};叠加多个检查
该属性可重复使用,因此可以在单个方法上叠加多个授权检查:
php
#[Authorize('create', Post::class)]
#[Authorize('update', 'post')]
public function save()
{
// Both checks must pass...
}何时不要使用
WARNING
#[Authorize] 属性仅保护操作的服务端执行,不会隐藏 Blade 模板中的 UI 元素。
仍应使用 Blade 的 @can 指令隐藏用户无权使用的按钮:
blade
@can('update', $post)
<button wire:click="save">Save</button>
@endcan了解更多
关于定义能力与策略的更多信息,请参阅 Laravel 授权文档。