In the world of web development, Laravel is a popular PHP framework that provides a wide range of features and tools to build web applications quickly and efficiently. One of its most useful features is middleware, which allows developers to filter HTTP requests entering their application.

However, while Laravel middleware is a powerful tool, there are times when it is important to exclude it from certain routes or controllers. In this blog post, we'll explore why excluding Laravel middleware can be essential for maintaining the security and performance of your web application.

Motivation

Three main reasons why excluding middleware on routes can be necessary:

  1. Performance Optimization: Some middleware functions can be resource-intensive, especially when dealing with large amounts of data or complex logic. By excluding middleware on routes where it's not needed, you can significantly improve the performance of your application.
  2. Security Requirements: Depending on your application's security requirements, you may need to exclude middleware on certain routes to prevent unauthorized access or protect sensitive data. For example, you may want to exclude middleware that logs user activity on routes that handle sensitive user information.
  3. Customization Needs: Sometimes, you may need to customize the behavior of certain routes or controllers in a way that conflicts with the functionality of certain middleware. In these cases, excluding middleware on those specific routes or controllers can be necessary to achieve the desired behavior.

Approaches

There is this way to remove attached route middleware (not global middleware) from a particular route, taken from the docs:

Route::get('/profile', function () {
    // ...
})->withoutMiddleware([MyCustomMiddleware::class]);

There's also this way which is not documented, but appears to work:

Route::group(['prefix' => 'prefix', 'excluded_middleware' => ['api']], function () {
    Route::get('/profile', function () {
        // ...
    });
});

On previous versions of Laravel, route middleware was displayed automatically using:

php artisan route:list

Currently, at least on laravel/framework version v9.52.4 the middleware is hidden by default. It is possible to display it using verbose or for short -v option:

php artisan route:list -v

In case you do not know it, the --path option is quite handy, combined with the above:

php artisan route:list --path user -v

Enjoy!