How to Apply Laravel Middleware to certain routes or exclude from certain routes

As you know Laravel Middleware can be applied to all the rotues in your controller by invoking the middleware method of Controller.

class UserController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

    }
}

In the above code auth middleware will applied to all the routes and methods under UserController.

Apply Middleware to only certain route.

 

class UserController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        $this->middleware('log')->only('index');
    }
}

With the above code auth middleware will be applied to all routes, and log middleware will be applied to index method of the Controller.

Livewire Component Library

Exclude route from Middleware

 

Host Laravel Application on DigitalOcean

Use coupon 5balloons on this Cloudways Affiliate URL to get special discount.
class UserController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth')->except('index');
        
        //Multiple exclude
        $this->middleware('log')->except(['index','privacy']);
    }
}

In the above code auth middleware will be applied to all the routes except index route. We can also include multiple routes to exclude by including routes in an array. Log middleware will be applied to all routes except two i.e. index and privacy.

This way you can skip middleware to be applied on certain routes.

Site Footer