Middleware — Laravel

Middleware is code that stands between the request and the controller. Create one with php artisan make:middleware EnsureApiKey, then fill in handle(Request…

Open the admin folder of your plain PHP project again. Each file probably starts with the same lines: session_start(), then an if (!isset($_SESSION['admin'])) that sends visitors to login.php. If one file is missing those lines, that page is open to anyone.

Middleware moves that check into one place. Middleware is code that stands between the request and the controller. Every request passes through middleware first. A middleware may inspect the request, refuse it, or pass it on to the controller. When the response comes out, the middleware holds that response again.

Picture walking into an office building. The guard at the gate checks every visitor. The receptionist on the admin floor only checks visitors to that floor. The key card is only on one room's door. If one post refuses you, you never reach the room. On the way home, you pass the same posts in reverse order. In Laravel, each post is one middleware, the room is the controller, and the way home is the response going out. The guard at the gate is like global middleware (for every request), the receptionist is like group middleware (for one area), and the key card is like middleware for one route.

What a middleware looks like

In the Library app, the /admin/dashboard page may only be opened by the staff app, which sends the header X-Api-Key: secret123. The value of that header is an API key: a secret text that proves the sender may come in. Create the middleware with Artisan:

php artisan make:middleware EnsureApiKey

Then fill in the file like this:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureApiKey
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->header('X-Api-Key') !== 'secret123') {
            return response()->json(['error' => 'Forbidden'], 403);
        }

        return $next($request);
    }
}

Before and after $next

Code above $next($request) runs while the request goes in. Code below it runs while the response comes out. For example LogRequest, a middleware that measures how long a request takes. microtime(true) is the current time in seconds:

class LogRequest
{
    public function handle(Request $request, Closure $next): Response
    {
        $start = microtime(true);                 // before: the request goes in

        $response = $next($request);              // the inner layers do their work

        $ms = round((microtime(true) - $start) * 1000);
        $response->headers->set('X-Took', $ms.'ms'); // after: the response comes out

        return $response;
    }
}

The route /admin/dashboard has LogRequest then EnsureApiKey. Before you look at the table, put them in order yourself: the two parts before $next, the controller, and the two parts after $next. Which runs first?

This is the trip of GET /admin/dashboard with the right key:

Step Layer What runs
1 LogRequest before $next: note the start time
2 EnsureApiKey before $next: the key matches, call $next
3 Controller answers 200 with {"message":"Welcome, admin!"}
4 EnsureApiKey after $next: no code, the response is passed out
5 LogRequest after $next: set the header X-Took: 18ms

The request goes in from the outermost layer to the inside, then the response comes out from the inside to the outside, like an onion peeled and then closed again. Each middleware is one layer of the onion, and the controller is in the middle.

When the key is wrong, steps 3 and 4 never happen: EnsureApiKey returns 403 without calling $next. Step 5 still runs. That 403 is also a response that travels out through LogRequest, so LogRequest still records it.

Attaching middleware: route, group, or global

A new middleware does nothing until it's attached. In Laravel 13, middleware is set up in bootstrap/app.php. Here LogRequest is attached for every request, and EnsureApiKey gets the alias (short name) api.key:

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware): void {
    $middleware->append(LogRequest::class);   // global: every request
    $middleware->alias([
        'api.key' => EnsureApiKey::class,     // a short name to use on routes
    ]);
})

Then the alias is used in the routes. A group is a set of routes that share the same settings. prefix('admin') adds /admin in front of the address of each route inside group(...):

// routes/web.php
Route::middleware('api.key')->prefix('admin')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/loans', [LoanController::class, 'index']);
});
Attached on How Applies to
Route ->middleware('api.key') after Route::get(...) that route only
Group Route::middleware('api.key')->group(...) every route inside the group: /admin/dashboard and /admin/loans
Global $middleware->append(EnsureApiKey::class) every request, including the /books catalogue that visitors open

The order: global first, then group, then route. Within one list, the order is from left to right. That is the order for your own middleware: Laravel moves some of its built-in middleware into the order of its own priority list. Laravel also comes with middleware that has ready aliases, such as auth (must be logged in), throttle:60,1 (at most 60 requests per minute), verified (email verified), and can:... for permission checks (see the Role-based Access Control lesson).

Ways to refuse

There are three ways to refuse a request in a middleware. abort() stops the request and answers right away with the status you give it:

Written in the middleware What the client receives
return response()->json(['error' => 'Forbidden'], 403); 403 with the body {"error":"Forbidden"}
abort(403, 'Wrong API key.'); 403. A client that asks for JSON gets {"message": "Wrong API key."}, a browser gets the Forbidden error page, which shows that message too
return redirect('/login'); 302 to /login. Right for web pages, not for an API

Middleware in a one-file editor

In the exercise, the editor has only one file. So the CheckApiKey class is written in the same file as the route, and attached with ->middleware(CheckApiKey::class). When it runs, the route is called like a real request, through your middleware. Without the right header, the output is GET /admin/dashboard → 403 then {"error":"Forbidden"}. A middleware is attached by its class name or its alias. A plain function name, such as ->middleware("checkApiKey"), ends in the error Target class [checkApiKey] does not exist.

⚠️ Doors left open, or every door locked

// .env
ADMIN_API_KEY=put-a-long-random-key-here

// config/services.php
'admin' => ['key' => env('ADMIN_API_KEY')],

// inside handle(), in place of the secret123 check
$key = (string) config('services.admin.key');
if ($key === '' || ! hash_equals($key, (string) $request->header('X-Api-Key'))) {
    return response()->json(['error' => 'Forbidden'], 403);
}

hash_equals() takes the same time however many characters match. So the key can't be guessed character by character from how long the answer takes. Laravel itself uses it to check CSRF tokens. $key === '' refuses every request when ADMIN_API_KEY was left empty. Without that check, a request with no header gets in, because two empty strings count as equal.

TL;DR: Middleware is code that stands between the request and the controller. Create one with php artisan make:middleware EnsureApiKey, then fill in handle(Request $request, Closure $next), where $next is the next layer (another middleware, or the controller). Refuse with return response()->json(['error' => 'Forbidden'], 403) or abort(403), pass on with return $next($request). Code before $next runs as the request goes in, and code after it as the response comes out. Each middleware is one layer: the outermost layer goes in first and comes out last. A refusal is still a response that travels out through the middleware around it. Attach to one route with ->middleware('auth') (auth: must be logged in), to an area (a set of routes) with Route::middleware(...)->group(...), or to every request with $middleware->append(...) in bootstrap/app.php. Aliases (short names for middleware) are registered in that file too.

⚡ A guard in front of the controller

Write:

public function handle(Request $request, Closure $next): Response
{
    if ($request->header('X-Api-Key') !== 'secret123') {
        return response()->json(['error' => 'Forbidden'], 403);
    }

    return $next($request);
}

Meaning: Middleware is code that stands between the request and the controller. php artisan make:middleware EnsureApiKey creates the class, and Laravel calls handle() for every request. When the X-Api-Key header (the API key) is wrong, the middleware answers 403 (not allowed) itself, and the controller never runs. When it's right, return $next($request) passes the request to the next layer: another middleware, or the controller.

⚡ In first, out last

Guess first: code after $next($request) runs as the response comes out. The route has LogRequest (a middleware that records how long each request takes) then EnsureApiKey, and the key is wrong. Does LogRequest's code after $next still run?

It does. The 403 from EnsureApiKey is a response too, and that response travels out through LogRequest, so it still gets recorded.

Meaning: Code before $next runs as the request goes in, code after it as the response comes out. The outermost layer goes in first and comes out last, like an onion: each middleware is one layer, and the controller is in the middle.

⚡ Attach it so it works

Write:

Route::middleware('api.key')->prefix('admin')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

Meaning: A new middleware does nothing until it's attached. This code attaches it through the alias api.key (a short name registered in bootstrap/app.php) to one group: every route inside it, whose address starts with /admin. The choices: ->middleware(...) for one route, a group for one area, $middleware->append(...) in bootstrap/app.php for every request.

In the exercise, attach the class: ->middleware(CheckApiKey::class). Laravel refuses a plain function name.

What you will learn