Skip to main content

概觀

Laravel 13 中,可透過 PHP Attributes 宣告 Controller 的中介層指派與授權檢查。取代原本的 middleware() 方法及 can 中介層,只需在類別或方法上直接加入 attribute 即可完成設定。
Controller 的 attributes 皆位於 Illuminate\Routing\Attributes\Controllers 命名空間下。

#[Middleware] — 指派中介層

套用於類別

在類別層級加上 #[Middleware],該中介層將套用至該 Controller 的所有 action。
要指派多個中介層時,重複標註 attribute 即可。

套用於方法

方法層級標註的中介層會與類別層級的中介層合併。

only / except 限定

在類別層級的 attribute 中指定 onlyexcept,可限定套用對象的方法。

Closure 中介層

Attribute 也可接受 closure。適合想以行內方式撰寫處理的場合。

與傳統 middleware() 方法的比較

使用 attribute 時無需實作 HasMiddleware 介面。但將 middleware() 方法與 attribute 混用可能導致預期外的行為,建議統一擇一使用。

#[WithoutMiddleware] — 排除中介層

將於類別層級套用的中介層,從特定方法或整個類別排除。

套用於方法

套用於類別及 only / except

若於類別層級加上 #[WithoutMiddleware],則包含子類別在內的所有 action 都會排除該中介層。可以 only / except 限定排除範圍。
#[WithoutMiddleware] 僅對路由中介層有效,無法排除註冊於 app/Http/Kernel.php 的全域中介層。

#[Authorize] — 透過 Policy 進行授權

作為 can 中介層的語法糖,可以 attribute 宣告透過 Policy 的授權檢查。

基本用法

Policy 的引數

第 2 個引數可傳入以下形式。

can 中介層的比較

不再需要在路由檔案中撰寫中介層,授權邏輯集中於 Controller。

實務範例

套用於 Resource Controller

套用於 API Controller

Attribute 的處理順序

當有多個 attribute 存在時,處理順序如下。
#[Authorize] 內部作為 can 中介層運作,因此於相同的 Pipeline 中處理。

總結:該使用哪一種?

下一步

PHP Attributes(Queue、Eloquent)

解說可用於 Queue Job 及 Eloquent 模型的 PHP Attributes。

中階:Controller

學習 Laravel Controller 的基本用法。
最後修改於 2026年8月2日