Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 67 ยท Routing and Controllers

Middleware

Learn Laravel middleware: make:middleware, handle() and $next, global, group and route middleware, parameters, terminable middleware and bootstrap/app.php setup.

Some work has to happen for many requests, regardless of which page was asked for: check that the user is signed in, verify a CSRF token, read the session, set a header, count requests per minute. Middleware is Laravel's answer. A middleware is a small class that sits between the incoming request and your route's action. It can look at the request, stop it with its own response, pass it on, and change the response on the way back out.

Laravel itself is built from middleware: sessions, cookie encryption, CSRF protection and authentication are all middleware classes. Understanding them explains a lot of behavior that otherwise looks magical. The underlying idea is not specific to Laravel; the middleware pipeline lesson in the PHP track builds one from scratch, and this lesson shows how Laravel packages it. Where middleware runs in a request is shown in the request lifecycle.

Laravel code is read-only here. The runnable examples are plain-PHP stand-ins for the pipeline, not the real framework classes.

The onion

Picture the request travelling inward through layers to your action. Each layer may act before passing the request to the next layer, and again after the response comes back.

flowchart LR
    R["Request"] --> M1["Middleware A<br/>before"]
    M1 --> M2["Middleware B<br/>before"]
    M2 --> C["Route action"]
    C --> M2b["Middleware B<br/>after"]
    M2b --> M1b["Middleware A<br/>after"]
    M1b --> S["Response sent"]

Layers run in order on the way in and in reverse order on the way out; any layer may answer early and skip the rest.

Writing a middleware

Generate a class with artisan:

Terminal
php artisan make:middleware EnsureTokenIsValid

It appears in app/Http/Middleware:

PHP
namespace App\Http\Middleware;

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

class EnsureTokenIsValid
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->header('X-Token') !== config('services.internal.token')) {
            return response('Forbidden', 403);        // stop here
        }

        return $next($request);                      // continue inward
    }
}

$next($request) hands the request to the next layer and returns that layer's response. Not calling it ends the chain. Whether your code runs before or after the action depends on where you put it:

PHP
public function handle(Request $request, Closure $next): Response
{
    // before: runs before the action
    $response = $next($request);
    // after: runs once the response exists
    $response->headers->set('X-Frame-Options', 'DENY');

    return $response;
}

Registering middleware

Since Laravel 11 there is no Kernel class: middleware is configured in bootstrap/app.php through withMiddleware():

PHP
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(web: __DIR__.'/../routes/web.php')
    ->withMiddleware(function (Middleware $middleware) {
        // Global: every request
        $middleware->append(\App\Http\Middleware\LogSlowRequests::class);

        // Add to an existing group
        $middleware->appendToGroup('web', \App\Http\Middleware\TrackVisitor::class);

        // Give a middleware a short alias for routes
        $middleware->alias([
            'token' => \App\Http\Middleware\EnsureTokenIsValid::class,
            'role'  => \App\Http\Middleware\EnsureUserHasRole::class,
        ]);

        // Tweak a built-in one
        $middleware->validateCsrfTokens(except: ['stripe/*']);
    })
    ->create();

There are three levels of attachment:

  • Global middleware (append and prepend) runs on every request, including API routes.
  • Group middleware runs for every route in a group. Laravel defines web (sessions, cookies, CSRF) and api for you. Routes loaded from routes/web.php are in the web group automatically, which is why a plain route gets sessions without any setup.
  • Route middleware is attached to individual routes or route groups.
PHP
Route::get('/reports', ReportController::class)->middleware('token');
Route::middleware(['auth', 'verified'])->group(function () { /* ... */ });
Route::get('/public-feed', FeedController::class)->withoutMiddleware('token');

Laravel ships useful aliases already: auth, guest, verified, throttle, can and signed, among others. Controllers can declare their own middleware, too.

The order matters. Global middleware runs first, then group middleware, then route middleware, each in the order listed. Laravel keeps a priority list for a few built-in classes (sessions before authentication, for instance) so that route-level ordering cannot break them.

Middleware parameters

Extra arguments follow the alias after a colon, separated by commas, and arrive as additional parameters of handle():

PHP
Route::put('/posts/{post}', UpdatePost::class)->middleware('role:editor,admin');

class EnsureUserHasRole
{
    public function handle(Request $request, Closure $next, string ...$roles): Response
    {
        if (! $request->user()?->hasAnyRole($roles)) {
            abort(403);
        }

        return $next($request);
    }
}

The same class can therefore protect many routes with different settings. For the built-in rate limiter this looks like throttle:60,1.

Terminable middleware

Sometimes work should happen after the response has been sent to the browser, such as writing a statistics record. Add a terminate method and Laravel calls it once the response has gone out (on servers that support finishing the response early, such as PHP-FPM):

PHP
class RecordVisit
{
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }

    public function terminate(Request $request, Response $response): void
    {
        // runs after the response is sent
        Visit::create(['path' => $request->path(), 'status' => $response->getStatusCode()]);
    }
}

Laravel resolves a fresh middleware instance for terminate. If handle and terminate must share state in properties, register the middleware as a singleton in a service provider. Heavy work still belongs in a queue, because terminate code runs in the web process.

Middleware or something else?

Use middleware for cross-cutting concerns that apply to many routes and that need the raw request: authentication gates, headers, locale detection, throttling. Business rules ("only the author may edit this post") belong in policies, and input rules belong in validation, because they depend on the specific resource and are easier to test in isolation.

A pipeline with aliases and parameters

This stand-in builds the onion with array_reduce, resolves aliases such as role:editor,admin into classes and parameters, and expands a group. It logs when each layer runs. Laravel's real pipeline is Illuminate\Pipeline\Pipeline, but the wrapping logic is the same.

PHP An onion pipeline with aliases and parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Observe that the guest and the reader never reach the action: the auth and role layers answered early, but the outer logging and header layers still saw and decorated those responses. That is the point of the onion.

Terminable work after the response

The next stand-in separates "send" from "terminate". A small kernel runs the pipeline, sends the response, then calls terminate() on every middleware that has one, mirroring how Laravel finishes a request.

PHP Terminable middleware runs after the response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The visit is saved only after "Response sent" is printed, so a slow terminate step would not delay what the visitor sees. As the lesson says above, in production heavy work still belongs in a queue.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens if a middleware's handle() method does not call $next($request)?

    Calling $next hands the request inward. Without it, the middleware must return its own response, which is how auth middleware rejects requests.
  2. 2. Where do you register global middleware in a Laravel 13 project?

    Modern Laravel configures middleware in bootstrap/app.php. The old Kernel class is gone from the default skeleton.
  3. 3. How do you pass the roles "editor" and "admin" to a route middleware aliased role?

    Parameters follow a colon, comma-separated, and become extra arguments of handle() after $next.
  4. 4. When does a terminate() method on a middleware run?

    Terminable middleware does follow-up work after the response goes out, though slow jobs still belong in a queue.
  5. 5. Which task is the best fit for middleware?

    Headers apply to many routes and need only the request and response. Resource rules fit policies, input rules fit validation, and totals belong in domain code.

Summary

  • Middleware wraps your route action in layers; each layer can act before and after it, or stop the request.
  • Create one with php artisan make:middleware; implement handle(Request $request, Closure $next).
  • Configure global, group and alias middleware in bootstrap/app.php with withMiddleware(); the web group gives sessions and CSRF.
  • Pass parameters with alias:value1,value2 and receive them as extra arguments.
  • Add terminate() for work after the response is sent; queue anything slow.
  • Use middleware for cross-cutting concerns, not for per-resource rules.

Next: The Service Container and Dependency Injection