Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I register middleware globally and selectively apply them to routes
    Laravel 11


Can I register middleware globally and selectively apply them to routes


Yes, you can register middleware globally and selectively apply them to specific routes in Laravel 11. Here's how to do it:

Registering Middleware Globally

To register middleware globally in Laravel 11, you need to modify the `bootstrap/app.php` file. Add the following code to register your middleware:

php
$app->withMiddleware(function ($middleware) {
    $middleware->append(
        \App\Http\Middleware\AdminMiddleware::class,
        \App\Http\Middleware\LogRequestMiddleware::class,
    );
});

This code registers the `AdminMiddleware` and `LogRequestMiddleware` globally, so they will be applied to all incoming requests.

Applying Middleware to Specific Routes

To selectively apply middleware to specific routes, you can use the `middleware` method when defining your routes in `routes/web.php` or `routes/api.php`. For example:

php
use App\Http\Controllers\YourController;

Route::get('/admin/dashboard', [YourController::class, 'dashboard'])
    ->name('admin.dashboard')
    ->middleware('admin');

Route::post('/api/create-post', [YourController::class, 'createPost'])
    ->middleware('api', 'log-request');

In this example:

- The `/admin/dashboard` route will only be accessible to users who pass the `admin` middleware, which is defined globally.
- The `/api/create-post` route will be protected by both the `api` and `log-request` middleware. The `api` middleware is a default middleware group in Laravel, while `log-request` is a custom middleware you can define.

Excluding Routes from Middleware

If you want to exclude certain routes from a globally registered middleware, you can use the `withoutMiddleware` method in your route definitions. For example:

php
Route::get('/public-page', [YourController::class, 'publicPage'])
    ->withoutMiddleware('admin');

This will allow the `/public-page` route to bypass the `admin` middleware, even though it is registered globally.

By combining global middleware registration and selective route middleware application, you can create a flexible middleware system that applies to all routes by default while allowing you to exclude or add specific middleware to individual routes as needed.

Citations:
[1] https://laracasts.com/discuss/channels/laravel/laravel-11-middleware
[2] https://laraveldaily.com/tip/adding-global-middleware-3-ways
[3] https://dev.to/msnmongare/how-to-register-middleware-in-laravel-11-3mkd
[4] https://stackoverflow.com/questions/78340907/how-do-i-register-a-middleware-in-laravel-11
[5] https://laravel.com/docs/11.x/middleware