用途
本技能用于在 Laravel 13 中把传统写法迁移为 PHP 属性(Attributes)写法,覆盖 Eloquent 模型、队列 Job、Console 命令、控制器、验证(FormRequest)、API 资源、工厂与种子器等组件。
主要能力
资料按组件列出了可用的属性:
- Eloquent:
#[Table]、#[Connection]、#[Fillable]、#[Hidden]、#[Visible]、#[Guarded]、#[Unguarded]、#[Appends]、#[Touches]、#[WithoutTimestamps]、#[WithoutIncrementing]、#[DateFormat]、#[Refreshes](13.33+);资料明确不提供#[Casts],应继续使用casts()方法。 - 队列 Job:
#[Connection]、#[Queue]、#[Tries]、#[Timeout]、#[Backoff]、#[MaxExceptions]、#[FailOnTimeout]、#[UniqueFor]、#[DeleteWhenMissingModels]、#[Delay](13.4+)、#[DebounceFor](13.6+)。 - Console:
#[Signature]、#[Description]。 - 控制器:
#[Middleware]、#[Authorize]、#[WithoutMiddleware](13.20+),命名空间为Illuminate\Routing\Attributes\Controllers。 - 验证:
#[RedirectTo]、#[RedirectToRoute]、#[ErrorBag]、#[StopOnFirstFailure]、#[FailOnUnknownFields],命名空间为Illuminate\Foundation\Http\Attributes。 - API 资源:
#[Collects]、#[PreserveKeys]。 - 工厂/测试:
#[UseModel]、#[Seed]、#[Seeder]、#[UnitTest](Illuminate\Foundation\Testing\Attributes)。 - 容器:
#[BindWhen](13.22+,PHP 8.5)及上下文属性(如#[Config]、#[Auth]等)。
使用方式
资料给出了示例代码。Eloquent 模型:
use Illuminate\Database\Eloquent\Attributes\{Table, Fillable, Hidden, Appends};
#[Table('flights')]
#[Fillable(['name', 'origin'])]
#[Hidden(['password'])]
#[Appends(['is_admin'])]
class Flight extends Model {}
队列 Job:
use Illuminate\Queue\Attributes\{Connection, Queue, Tries, Backoff};
#[Connection('redis')]
#[Queue('podcasts')]
#[Tries(5)]
#[Backoff([10, 30, 60])]
class ProcessPodcast implements ShouldQueue {}
资料还描述了一套工作流:在实现前并行启动三个代理(fuse-ai-pilot:explore-codebase 扫描旧属性、fuse-ai-pilot:research-expert 核对 Laravel 13 发布说明、mcp__context7__query-docs 拉取官方文档示例),实现后运行 fuse-ai-pilot:sniper 验证。这些代理与工具的具体行为与可用性,资料暂未提供细节。
适用场景
适合在 Laravel 13 项目中把 $fillable、$hidden、$table、$connection、$tries、$timeout、$backoff、$signature、$description 等传统属性,以及控制器构造函数中的中间件/授权配置、FormRequest 重定向配置,改写为属性声明的重构工作。
限制与注意事项
- 不要在同一类中混用属性与旧式属性:例如
#[Fillable(['name'])]与protected $fillable = [...]并存时,Laravel 会静默忽略其中一种,具体哪一方的优先级,可能随环境不同而变化。 - Eloquent 与 Job 属性只能用于类级,不能标在方法上;控制器的
#[Middleware]、#[Authorize]也可用于公开 action 方法。 - 子类属性与父类属性会累加合并,需要覆盖时应重新声明。
- 需导入正确命名空间:Eloquent 用
Illuminate\Database\Eloquent\Attributes\*,Job 用Illuminate\Queue\Attributes\*。 - 不要在缺少底层 Policy(自动发现、
Gate::policy()或#[UsePolicy])时给控制器 action 加#[Authorize]。 - 添加属性后应删除遗留的
$tries、$backoff、$timeout等属性,避免重复。 - 资料中关于各 Laravel 版本号对应属性的说明,应以官方发布说明为准;本文未对其进行额外核实。