MasterPHP.in
Try Compiler →
Laravel Tutorial

Middleware Aliases, Groups and Parameters in Laravel


In the last lesson you wrote two middleware for your invoice app. They work, but every route that uses them needs the full class name, which makes route files long and noisy. Now the owner has new requests. The sales reports page must be open only to admins and managers, not to every staff member. The response time header should appear on every page, without adding it to each group by hand. And Razorpay’s payment callback keeps failing with 419 | Page Expired, because it cannot send a CSRF token.

All of these are solved in one file: bootstrap/app.php. In this lesson you will learn how to give middleware short names, run middleware on every request, bundle middleware into groups, pass settings to middleware, and exclude a route from CSRF checking.

 

The Problem with Class Names Everywhere

This is how your routes look right now:

use App\Http\Middleware\AddResponseTimeHeader;
use App\Http\Middleware\EnsureStaffIsLoggedIn;

Route::middleware([EnsureStaffIsLoggedIn::class, AddResponseTimeHeader::class])
    ->group(function () {
        Route::resource('invoices', InvoiceController::class);
    });

It works, but you must import each class in every route file, repeat the same pair wherever you need them, and read a long line to understand a simple idea. Compare that with the routes you saw in the Middleware Basics lesson, such as ->middleware('auth'). A short name is easier to write and to read.

 

Where Middleware Is Configured

In modern Laravel, middleware is configured in bootstrap/app.php. There is no app/Http/Kernel.php file, which is where older tutorials tell you to register middleware. Open bootstrap/app.php and find this part:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

Everything in this lesson goes inside the withMiddleware function, where the $middleware object lets you change how middleware behaves. The withRouting part is where your route files are connected, as you saw in the Request Lifecycle lesson.

 

Middleware Aliases

An alias is a short name for a middleware class. Register aliases with the alias() method. Remember to import the classes at the top of the file:

use App\Http\Middleware\EnsureStaffIsLoggedIn;

->withMiddleware(function (Middleware $middleware): void {
    $middleware->alias([
        'staff' => EnsureStaffIsLoggedIn::class,
    ]);
})

Now your routes no longer need the class or its import:

Route::middleware('staff')->group(function () {
    Route::resource('invoices', InvoiceController::class);
});

You have already been using aliases without knowing it. The names auth, throttle, verified and guest all exist because Laravel registers them for you. Avoid giving your own middleware one of these names, because yours would replace the built-in one.

 

Global Middleware

Global middleware runs on every request, whichever route is used. Add to the global list with append(), which adds to the end, or prepend(), which adds to the beginning:

use App\Http\Middleware\AddResponseTimeHeader;

->withMiddleware(function (Middleware $middleware): void {
    $middleware->append(AddResponseTimeHeader::class);
})

Now every page, including routes that do not belong to any group, gets the X-Response-Time header. Use global middleware only for things that are truly needed everywhere. The staff check from the last lesson must not be global, because it reads the session, and global middleware runs before the session is started.

 

Middleware Groups

A group bundles several middleware under one name. You already know the built-in web and api groups. You can define your own with group():

->withMiddleware(function (Middleware $middleware): void {
    $middleware->alias([
        'staff' => EnsureStaffIsLoggedIn::class,
    ]);

    $middleware->group('staff-area', [
        'staff',
        AddResponseTimeHeader::class,
    ]);
})

A group can contain aliases and class names together. Use the group exactly like a single middleware:

Route::middleware('staff-area')->group(function () {
    Route::resource('invoices', InvoiceController::class);
});

Choose group names that do not clash with web or api.

 

Adding to the Built-in Groups

You can also add your own middleware to the web and api groups, so that every route in routes/web.php or routes/api.php gets it automatically:

->withMiddleware(function (Middleware $middleware): void {
    $middleware->web(append: [
        AddResponseTimeHeader::class,
    ]);

    $middleware->api(prepend: [
        // middleware that should run first on API routes
    ]);
})

Because the middleware is added to the web group, it runs after the session has started. This makes the web group the right place for session-based checks that should apply everywhere in the web routes.

 

Removing or Replacing Default Middleware

Laravel also lets you remove or replace entries from the default lists:

$middleware->remove(\Illuminate\Http\Middleware\TrustProxies::class);

$middleware->replace(OldMiddleware::class, NewMiddleware::class);

Do this only when you have a clear reason. The default middleware protects your app in ways that are easy to forget, so removing one without understanding it can open a security hole.

 

Middleware Parameters

So far a middleware either runs or it does not. Sometimes you want to give it a setting. Your reports page should allow admins and managers, while another page may allow only admins. Instead of writing a separate middleware for every role, write one and pass the role as a parameter.

You already used a parameter in the Middleware Basics lesson, in throttle:3,1. The text after the colon is the parameter list, and the values are separated by commas.

Create the middleware:

php artisan make:middleware EnsureStaffHasRole

Parameters arrive as extra arguments in handle(), after $next:

public function handle(Request $request, Closure $next, string ...$roles): Response
{
    $role = $request->session()->get('staff_role');

    if (! in_array($role, $roles, true)) {
        abort(403, 'You do not have permission to open this page.');
    }

    return $next($request);
}

The three dots in string ...$roles collect any number of values into an array. Register an alias, then use it with parameters:

$middleware->alias([
    'staff' => EnsureStaffIsLoggedIn::class,
    'role'  => EnsureStaffHasRole::class,
]);


Route::middleware('staff')->group(function () {
    Route::resource('invoices', InvoiceController::class);

    Route::get('/reports', fn () => 'Sales reports')
        ->middleware('role:admin,manager')
        ->name('reports.index');
});

The route /reports is open to admin or manager, and a plain staff member gets a 403 page. A route that needs only admins would use ->middleware('role:admin'). The staff middleware runs first, then role, because middleware runs in the order you list it, as you learned earlier.

The staff_role value comes from your temporary demo login. Update the demo route from the last lesson to try it:

Route::get('/demo/staff-login', function () {
    session(['staff_id' => 1, 'staff_role' => 'manager']);

    return redirect()->route('invoices.index');
});

This hand-made role check is only for learning. In the Authorization chapter you will replace it with Laravel’s real tools, including roles and permissions with Spatie.

 

Excluding Routes from CSRF Protection

In the Single Action Controllers lesson, we left a problem open. Razorpay sends a POST request to your callback route, but it cannot send your CSRF token, so Laravel rejects it with 419 | Page Expired. The fix is also in bootstrap/app.php. In Laravel 13, the CSRF middleware is configured with preventRequestForgery():

->withMiddleware(function (Middleware $middleware): void {
    $middleware->preventRequestForgery(except: [
        'payments/razorpay/callback',
    ]);
})

Write the address without the domain, as in the example. A wildcard such as payments/razorpay/* also works. Older tutorials call this middleware VerifyCsrfToken and use a different method, so use the Laravel 13 name.

Removing CSRF protection from a route means anyone on the internet can send requests to it. Keep the list as short as possible, and when you build the real callback, verify the signature that Razorpay sends with each request, so you know the call is genuine.

 

Cookies That Laravel Should Not Decrypt

The same file solves the cookie problem from the Sessions & Cookies lesson, where a cookie set by JavaScript was read as null. List its name as an exception:

$middleware->encryptCookies(except: [
    'theme',
]);

Laravel will now read the theme cookie as plain text. There are similar methods for other defaults, such as trimStrings() for input trimming.

 

Putting It Together

Here is the full withMiddleware section after this lesson, with the imports it needs:

use App\Http\Middleware\AddResponseTimeHeader;
use App\Http\Middleware\EnsureStaffHasRole;
use App\Http\Middleware\EnsureStaffIsLoggedIn;
use Illuminate\Foundation\Configuration\Middleware;

->withMiddleware(function (Middleware $middleware): void {
    $middleware->alias([
        'staff' => EnsureStaffIsLoggedIn::class,
        'role'  => EnsureStaffHasRole::class,
    ]);

    $middleware->append(AddResponseTimeHeader::class);

    $middleware->preventRequestForgery(except: [
        'payments/razorpay/callback',
    ]);
})

Run php artisan route:list -v to confirm that the right middleware appears under each route.

 

Common Mistakes

Mistake 1: Following Laravel 10 Tutorials

Older tutorials tell you to open app/Http/Kernel.php and edit $middlewareAliases or $middlewareGroups. That file does not exist in a Laravel 11 or newer project. If you search for it and cannot find it, you are reading an outdated guide. Everything in this lesson replaces it.

 

Mistake 2: Alias Not Registered, or Class Not Imported

Route::middleware('staff')->group(function () {
    // ...
});

If the alias is misspelled, or was never added to bootstrap/app.php, Laravel looks for a class named staff:

Illuminate\Contracts\Container\BindingResolutionException: Target class [staff] does not exist.

The same error appears if you write EnsureStaffIsLoggedIn::class in bootstrap/app.php without importing the class at the top. Check the alias spelling and the use lines.

 

Mistake 3: Forgetting the Parameter

Route::get('/reports', ...)->middleware('role');

With string ...$roles, no value means an empty list, so no one matches and every visitor gets a 403 page. There is no error to explain it. If a role-based route blocks everyone, check that the parameter is written after the colon.

 

Mistake 4: Wrong Spelling or Capital Letters in a Parameter

->middleware('role:Admin')

Parameters are plain text, and the comparison in the middleware is case-sensitive. The value Admin does not match admin, and the visitor is refused. Use the same spelling everywhere, and keep roles in lowercase.

 

Mistake 5: Making Session-Based Middleware Global

$middleware->append(EnsureStaffIsLoggedIn::class);

Global middleware runs before the session starts, so the staff check fails with:

RuntimeException: Session store not set on request.

Attach it to a route group, or add it to the web group with $middleware->web(append: [...]).

 

Mistake 6: Excluding Too Much from CSRF

Writing a wide pattern like '*' or 'payments/*' to make a 419 error go away turns off protection for far more routes than needed. Exclude only the exact address that must receive outside requests, and verify the sender in the controller.

 

Quick Summary

  • Middleware is configured in bootstrap/app.php, inside withMiddleware, and there is no Kernel.php in Laravel 11 and newer.
  • $middleware->alias(['staff' => EnsureStaffIsLoggedIn::class]) gives a middleware a short name, and you then write ->middleware('staff').
  • append() and prepend() add global middleware that runs on every request, so avoid using sessions there.
  • group('staff-area', [...]) bundles middleware under one name.
  • web(append: [...]) and api(prepend: [...]) add middleware to the built-in groups.
  • Pass parameters after a colon, such as role:admin,manager, and receive them as extra arguments in handle().
  • Use string ...$roles to accept any number of values.
  • preventRequestForgery(except: [...]) excludes exact addresses from CSRF checking in Laravel 13.
  • encryptCookies(except: [...]) lets Laravel read cookies that were not created by Laravel.
  • Keep exclusions as small as possible, and verify outside callers yourself.
  • Run php artisan route:list -v to check the result.

 

What’s Next

That completes the chapter on requests, responses and middleware. You can now read input, return pages and files, remember visitors with sessions and cookies, and control the flow of every request. So far, all the pages you returned were plain text, JSON or a few lines of HTML. In the next chapter, you will learn how to build real pages. The first lesson, Blade Basics & Displaying Data, shows you how Laravel’s template engine turns your data into clean HTML.

Frequently Asked Questions

An alias is a short name for a middleware class. You register it in bootstrap/app.php with the alias method, and then use the short name on routes, like middleware(‘staff’). It makes route files shorter and easier to read.
Write the parameters after a colon in the middleware name, separated by commas, such as role:admin,manager. In the middleware class, they arrive as extra arguments in the handle method after the next function. Use a variadic argument like string ...$roles to accept any number of values.
Prepend adds a middleware to the beginning of a list, so it runs first. Append adds it to the end, so it runs last among the middleware in that list. The order matters when one middleware depends on another.
Use the preventRequestForgery method inside withMiddleware in bootstrap/app.php, and pass the addresses in the except array. Write the address without the domain, for example payments/razorpay/callback. Older tutorials use VerifyCsrfToken for this, which was renamed in Laravel 13.
Use a group when several routes need the same set of middleware, or when you want one name for a bundle of checks. It keeps routes short and makes sure that a new route inside the group gets the same protection. For a single route with one middleware, listing it directly is fine.

Share this tutorial