#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →

Applying Middleware to Routes

A middleware class only takes effect once it's actually attached to a route or group of routes. Laravel offers several ways to do this, depending on how broadly the middleware should apply.

Applying Middleware to a Single Route

The most direct approach is chaining the middleware() method onto an individual route definition, listing one or more middleware by their registered name or class.

Applying Middleware to a Group of Routes

When several routes need the same middleware, wrapping them in a Route::middleware([...])->group() call avoids repeating the same call on every single route.

ApproachExample
Single routeRoute::get('/dashboard', ...)->middleware('auth')
Grouped routesRoute::middleware(['auth'])->group(function () {...})
Controller constructor$this->middleware('auth') inside a controller

Stacking Multiple Middleware

Some middleware should run on every single request, while others should only apply to a handful of routes — understanding that distinction is the focus of the next topic.

Registering a Short Name for Your Middleware

Before you can write ->middleware('role'), Laravel must know which class that name points to. Where you register it depends on the framework version.

// Laravel 11 and later: bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'role' => \App\Http\Middleware\EnsureUserHasRole::class,
    ]);
})

// Laravel 10 and earlier: app/Http/Kernel.php
protected $middlewareAliases = [
    'role' => \App\Http\Middleware\EnsureUserHasRole::class,
];

You can also skip the alias and pass the class directly: ->middleware(EnsureUserHasRole::class).

Passing Parameters to Middleware

Many checks need extra information, such as which role is allowed. Add values after a colon, separated by commas, and receive them as extra arguments in handle().

Route::get('/reports', [ReportController::class, 'index'])
    ->middleware('auth', 'role:admin,manager');

// app/Http/Middleware/EnsureUserHasRole.php
public function handle(Request $request, Closure $next, string ...$roles)
{
    if (! in_array($request->user()?->role, $roles, true)) {
        abort(403);
    }
    return $next($request);
}

Here auth runs first and makes sure a user is logged in, then the role check runs. Listing them in this order matters, because the role check needs a user to inspect.

Each middleware either passes the request on by calling $next($request) or stops it by returning a response or aborting. Because every layer wraps the next, code written after $next() runs on the way back out, which is where you would add response headers or timing logs.

Controller Middleware in Newer Laravel

From Laravel 11, the base controller no longer provides $this->middleware() in the constructor. Instead, a controller implements HasMiddleware and returns its middleware from a static method, with optional only and except filters.

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

class InvoiceController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            'auth',
            new Middleware('role:accountant', only: ['store', 'update']),
            new Middleware('throttle:30,1', except: ['index']),
        ];
    }
}

Excluding a Route From Group Middleware

Sometimes one route inside a protected group must stay open, such as a public status page. Use withoutMiddleware() on that route instead of moving it out of the group.

Route::middleware(['auth'])->group(function () {
    Route::get('/account', [AccountController::class, 'show']);
    Route::get('/status', StatusController::class)->withoutMiddleware('auth');
});

Note that withoutMiddleware removes only route middleware. Global middleware, which runs on every request, cannot be removed this way.

Checking and Debugging

  • Run php artisan route:list -v to see which middleware is attached to each route.
  • Use middleware groups such as web and api for cross-cutting needs like sessions, CSRF protection and throttling, and keep route-level middleware for specific checks.
  • If a route returns 403 or redirects to login unexpectedly, check whether a group higher up added the middleware.
  • Keep middleware focused on one job; heavy business logic belongs in controllers or services.
  • Write a feature test for each protected route that confirms guests and wrong roles are blocked.
  • Prefer named routes and aliases over long class names to keep route files readable.
  • Remember that route caching (php artisan route:cache) stores middleware assignments too; clear or rebuild the cache after changing them on a server.

Ready to master Laravel Training Course?

Join Uncodemy's hands-on Laravel program and build real, production-ready applications.

Explore Course