How to Exclude Middleware in Specific Laravel Routes

Middleware in Laravel plays a crucial role in intercepting HTTP requests entering the application, to apply custom logic, before any of the actual application code is executed. However, there are scenarios where you may need to exclude certain routes or methods from middleware processing.

In this tutorial, we will explore various methods to exclude middleware for specific routes, or controller methods, in Laravel. We will cover customizing how middleware is added in the route files and by inline middleware in the controller.

Note that in Laravel 11+ the syntax to use controller middleware has changed. The examples in this tutorial will cover both the new and old syntax. The syntax for adding middleware to your route files, like web.php and api.php, remains unchanged compared to Laravel 10 and lower.

Let’s dive in!

Method 1: Excluding Middleware in Routes by using withoutMiddleware

You can exclude some routes from using a middleware by applying withoutMiddleware on routes in web.php or api.php.

In the following example we use a group to assign middleware web and auth while making the route /public/profile an exception and remove the middleware from it:

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

// Apply Middleware group to routes
Route::group(['middleware' => ['web', 'auth']], function () {
    // Route with middleware `web` and `auth`
    Route::get('/dashboard', [UserController::class, 'dashboard']);

    Route::get('/profile', [UserController::class, 'profile']);

    // Route without middleware `auth` (but has still has `web`)
    Route::get('/public-profile', [UserController::class, 'publicProfile'])
        ->withoutMiddleware('auth');
});

Method 2: Excluding Middleware in a Controller by Using except()

To exclude middleware for specific routes in a controller, you can use except() when applying Middleware in your controller code.

To use `except` in Controller middleware in Laravel 11+ use the following code:

app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
 
class UserController extends Controller implements HasMiddleware
{
    /**
     * In Laravel 11+ defines Middleware of a controller in a static middleware() function
     */
    public static function middleware(): array
    {
        return [
            'auth',
            new Middleware('auth', except: ['showPublicProfile']),
        ];
    }
    
    public function index() {}
    public function show() {}
    public function showPublicProfile() {}
}

To use `except` in Controller middleware in Laravel 10 and older use the following code:

app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * In Laravel 10 and older, controller middleware is set in the __construct method
     */
    public function __construct()
    {
        $this->middleware('auth')->except(['showPublicProfile']);
    }

    public function index() {}
    public function show() {}
    public function showPublicProfile() {}
}

In these examples, the auth middleware is applied to all methods in the UserController except for the showPublicProfile method.

Method 3: Excluding Middleware in a Controller by Using only()

You can use the only() method to explicitly specify which routes should have a specific middleware applied.

To use `only` in Controller middleware using Laravel 11 use the following code:

app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
 
class UserController extends Controller implements HasMiddleware
{
    /**
     * In Laravel 11+ defines middleware of a controller in a static middleware() function
     */
    public static function middleware(): array
    {
        return [
            'auth',
            new Middleware('auth', only: ['index', 'show']),
        ];
    }
    
    public function index() {}
    public function show() {}
    public function showPublicProfile() {}
}

The following implementation of UserController demonstrates this:

app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;

class UserController extends Controller
{
    /**
     * In Laravel 10 and older, controller Middleware is set in the __construct method
     */
    public function __construct()
    {
        $this->middleware('auth')->only(['index', 'show']);
    }

    public function index() {}
    public function show() {}
    public function showPublicProfile() {}
}

In these examples, only the index and show methods will have the auth middleware applied.

Frequently Asked Questions

Can I Use except and only at the Same Time in Inline Controller Middleware?

You can use except and only at the same time. The following code is an example of how this can be done:

<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class UserController extends Controller implements HasMiddleware
{

    public static function middleware(): array
    {
        return [
            'auth',
            new Middleware('log', only: ['index']),
            new Middleware('subscribed', except: ['store']),
        ];
    }

    public function index() {}
    public function store() {}
}

Conclusion

In Laravel, excluding middleware for specific routes or methods provides flexibility in handling requests. By using methods such as except, only(), or withoutMiddleware, you can finetune the middleware behavior specifically for different parts of your application.

Feel free to use these exclusions to achieve finer control over middleware in your own projects. Let me know if this has been helpful and, if you’d like, how you are using middleware in your application by commenting below.

Happy coding!

References

Johan van den Broek

Johan is the creator of laracoding.com. As a child, he began tinkering with various programming languages, many of which have been long forgotten today. Currently, he works exclusively with PHP and Laravel, and his passion for programming remains to this day.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts