Middleware
Middleware can inspect a request, stop it early, or add something to the returned response. Choose the registration scope according to which requests need the behavior. The snippets build on the articles API and use application middleware classes for timing and logging.
Global middleware
Register global middleware in Application::middlewares(). It runs before routing, so a request ID is available even when no route matches.
use Atom\Http\MiddlewareRegistry;
use Atom\Http\RequestIdMiddleware;
protected function middlewares(MiddlewareRegistry $middlewares): void
{
$middlewares->add(RequestIdMiddleware::class);
}
Group middleware
Inside bootstrap(), attach ArticleController inside a group. The group prefixes its routes with /v1 and applies ArticleApiTiming to all of them. Use this registration in place of attaching the controller separately.
Route::group("/v1", static function (): void {
Route::attach(ArticleController::class);
})->middleware(ArticleApiTiming::class);
Controller middleware
Inside ArticleController.php, add middleware to the class attribute to run it on every route attached from that controller.
#[Controller("/api/articles", middleware: ArticleRequestLogging::class)]
Single-route middleware
Add middleware to the specific method attribute that declares the route. Here it applies to GET. The HEAD route uses the same handler but has its own attribute.
#[Get("{slug}", middleware: ArticleReadMetrics::class)]
#[Head("{slug}")]
For a route registered directly, call middleware() on the route entry instead:
Route::get("/api/articles/{slug}", [ArticleController::class, "show"])
->middleware(ArticleReadMetrics::class);
Execution order
For GET /v1/api/articles/building-atom with the grouped controller and attributes above, Atom enters middleware in this order:
- Global middleware, before route matching.
- Group middleware, from outer groups to inner groups.
- Controller middleware.
- Middleware on the matched route attribute.
- The
show()handler.
Middleware at the same level runs in registration order. Each layer can call the next handler and then modify the response as it returns in reverse order. A layer that returns early prevents the inner layers and route handler from running.