How to define global middleware in Laravel 11

September 20th, 2024 • 2 minutes read time

Since Laravel removes the Kernel class for registering middleware, here's how to define global middleware in your Laravel apps.

Everything we'll discuss here happens in the bootstrap/app.php file, so open that up and let's get started!

If you simply need to push some global middleware in Laravel, use the append method on the Middleware object inside withMiddleware:

->withMiddleware(function (Middleware $middleware) {
     $middleware->append(TouchUserLastActivity::class);
})

This pushes the TouchUserLastActivity middleware to the end of the default list of middleware Laravel runs by default.

You're also able to prepend if you want the middleware to be included first:

->withMiddleware(function (Middleware $middleware) {
     $middleware->prepend(TouchUserLastActivity::class);
})

The examples above assume the middleware is run for both web and api route groups.

To add middleware specifically for web, use the web method and append argument:

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(
        append: [
            TouchUserLastActivity::class
        ]
    );
}

Since this is an array, you can append as many middlewares as you like.

And of course, you're also able to prepend to web too:

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(
        prepend: [
            TouchUserLastActivity::class
        ]
    );
}

You can do the same thing for your api route group (both for prepend and append). Just use the api method instead:

->withMiddleware(function (Middleware $middleware) {
    $middleware->api(
        prepend: [
            TouchUserLastActivity::class
        ]
    );
}

If you need more control over the middleware stack, you can completely override it to adjust what you need.

Here's an example directly from the Laravel documentation:

->withMiddleware(function (Middleware $middleware) {
    $middleware->use([
        // \Illuminate\Http\Middleware\TrustHosts::class,
        \Illuminate\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        TouchUserLastActivity::class, // Our new middleware, placed exactly where we need it
        \Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Http\Middleware\ValidatePostSize::class,
        \Illuminate\Foundation\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ]);
})
If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!