How to Create Custom Middleware in Laravel 13

Custom middleware in Laravel 13 lets you run your own checks โ€” role checks, logging, request limits โ€” before a request ever reaches a controller. This tutorial shows how to create middleware with Artisan, write the handle() method, register it the Laravel 13 way in bootstrap/app.php, attach it to routes and controllers, and fix the four mistakes that stop middleware from running at all.

RH Raja HunainAuthor 02 Dec 2026 2 min read 8 views
Table of Contents
Share

Every request to a Laravel app passes through a stack of middleware before it reaches a controller. Authentication, sessions, and CSRF protection are all middleware โ€” small classes that inspect a request, and either let it through, change it, or stop it. When the built-in middleware does not cover your rule, you write your own: a role check, a subscription check, request logging, or a maintenance switch for one part of the site.

What middleware actually does

Think of middleware as a checkpoint on the road to your controller. A request enters the app, passes through each middleware in turn, and only reaches the controller if every checkpoint lets it through. Each middleware receives the request and a $next closure. Calling $next($request) hands the request to the next checkpoint; returning anything else โ€” a redirect, a JSON error, an abort โ€” stops the journey there.

Anything you write before return $next($request) runs on the way in, and anything after it runs on the way out, once the controller has produced a response. That is why the same mechanism works for both jobs: checking a user before the controller runs, and adding a header or logging the result after it finishes.

Step 1: Generate the middleware class

Laravel creates the class for you with one Artisan command. Open a terminal in your project root and run:

php artisan make:middleware EnsureUserIsEditor

This creates app/Http/Middleware/EnsureUserIsEditor.php with a ready-made skeleton:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserIsEditor
{
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }
}

The skeleton passes every request straight through. Your logic goes inside handle(), before the return $next($request) line.

Step 2: Write the check inside handle()

A common real-world example is a role check: only users with the editor role may reach the article editor. Here is the complete middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserIsEditor
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if ($user === null || $user->role !== 'editor') {
            abort(403, 'Only editors can access this page.');
        }

        return $next($request);
    }
}

The null check comes first: if nobody is logged in, $request->user() is null, and reading ->role on it would crash. abort(403) returns immediately โ€” the controller never runs, which is exactly what a guard should do.

A second useful pattern is a logging middleware that records how long each request took:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class LogRequestTime
{
    public function handle(Request $request, Closure $next): Response
    {
        $startedAt = microtime(true);

        $response = $next($request);

        $ms = round((microtime(true) - $startedAt) * 1000, 2);
        Log::info($request->method() . ' ' . $request->path() . " took {$ms} ms");

        return $response;
    }
}

This one stores the result of $next($request), does its work afterwards, and returns the response โ€” the right place for anything that needs the finished response.

Step 3: Register it the Laravel 13 way

This is the step where most people get stuck: Laravel 11 removed the old app/Http/Kernel.php file, and Laravel 13 keeps that change. Middleware is registered in bootstrap/app.php, inside the withMiddleware() callback.

Open bootstrap/app.php. You will see something like this:

<?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) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

There are three ways to register your middleware, and you pick the one that matches how widely it should run.

Run it on every request (global). Use append() to add it to the end of the global stack, or prepend() to run it first:

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

Add it to the web or api group. The web group runs on every route in routes/web.php; the api group runs on routes/api.php. This is the right choice when the check belongs to a whole section of the app:

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

Give it a short alias for single routes. An alias is a nickname you can attach to individual routes. This is the most common choice for a role check:

use App\Http\Middleware\EnsureUserIsEditor;

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

Do not forget the use import at the top of bootstrap/app.php โ€” without it, PHP cannot find your class and the app fails to boot.

Step 4: Attach the middleware to routes

With the alias registered, attaching it to a route is one method call:

use Illuminate\Support\Facades\Route;

Route::get('/articles/create', [ArticleController::class, 'create'])
    ->middleware('editor');

Route::get('/articles/{article}/edit', [ArticleController::class, 'edit'])
    ->middleware('editor');

For a whole section, wrap the routes in a group so you write the middleware once:

Route::middleware('editor')->group(function () {
    Route::get('/articles/create', [ArticleController::class, 'create']);
    Route::get('/articles/{article}/edit', [ArticleController::class, 'edit']);
    Route::delete('/articles/{article}', [ArticleController::class, 'destroy']);
});

You can stack middleware on one route. Laravel runs them in the listed order, so put auth first when your check needs a logged-in user:

Route::get('/dashboard', [DashboardController::class, 'index'])
    ->middleware(['auth', 'editor']);

If editor runs before auth, $request->user() is still null and even a logged-in editor gets a 403.

Laravel 13 also lets you attach middleware directly to a controller, which keeps the route file clean when the whole controller needs the same check:

<?php

namespace App\Http\Controllers;

use App\Http\Middleware\EnsureUserIsEditor;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class ArticleController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware(EnsureUserIsEditor::class, only: ['create', 'edit']),
        ];
    }
}

The only option limits the check to the listed methods; use except for the opposite โ€” run it on every method except the ones you name. The implements HasMiddleware part is not optional: without it, Laravel never calls the static middleware() method and the check silently never runs.

Step 5: Pass parameters to your middleware

One middleware can serve several roles โ€” pass the role as a parameter after a colon:

Route::get('/admin', [AdminController::class, 'index'])
    ->middleware('role:admin');

Route::get('/moderation', [ModerationController::class, 'index'])
    ->middleware('role:moderator');

The parameter arrives as an extra argument in handle(), after $next:

public function handle(Request $request, Closure $next, string $role): Response
{
    if ($request->user()?->role !== $role) {
        abort(403);
    }

    return $next($request);
}

You can pass several parameters separated by commas โ€” ->middleware('role:admin,editor') โ€” and they arrive as separate arguments in order.

Four mistakes that stop middleware from running

Most middleware problems are one of these four, and each has a clear fix.

1. Registering it in Kernel.php. If you followed an old tutorial and created app/Http/Kernel.php, Laravel 13 ignores it completely โ€” registration only counts in bootstrap/app.php. Move it there and delete the kernel file.

2. Using an alias that was never registered. The error looks like Target class [editor] does not exist. It means the route uses the alias but bootstrap/app.php has no matching alias() entry. Check the spelling in both places โ€” aliases are case-sensitive.

3. Calling $request->user() before auth runs. If your middleware runs before auth, or is global while the web group (which starts the session and loads the user) runs after it, the user is null. List auth first, or add your middleware to the web group instead.

4. Forgetting return $next($request). If handle() ends without returning anything, Laravel has no response to send and the page comes back blank. Every path through handle() must end in a return $next($request) or a returned response such as a redirect or an abort.

For debugging, run php artisan route:list -v: it shows every route with its middleware, so you can see in seconds whether yours is attached.

Terminable middleware: running code after the response

Code after $next($request) still runs before the response reaches the browser. If work must happen after the response has already been sent โ€” for example, writing a heavy analytics record without slowing the page down โ€” give the middleware a terminate() method:

public function terminate(Request $request, Response $response): void
{
    Log::info('Response sent for ' . $request->path());
}

Laravel calls terminate() after the response is sent. Keep it fast and failure-proof, because the user never sees its result.

Wrapping up

Custom middleware is one of the smallest building blocks in Laravel, and also one of the most reused. Generate the class with Artisan, put your check in handle(), register it in bootstrap/app.php โ€” globally, in a group, or as an alias โ€” and attach it to the routes that need it. Keep the check small and single-purpose, remember that auth must run before any check that reads the user, and always return $next($request) on the success path.

If your API routes need the same protection, How to Create a REST API in Laravel 13 shows how a Laravel 13 API is put together, and the same registration rules apply in routes/api.php. If a request is blocked before your middleware runs, the cause is often session or CSRF โ€” see How to Fix 419 Page Expired Error in Laravel.

Frequently asked questions

Why is my middleware not running at all? Usually because it was registered in the old app/Http/Kernel.php, which Laravel 13 ignores. Register it in bootstrap/app.php instead, then check with php artisan route:list -v that it is attached to the route.

Can I use middleware on API routes? Yes. Register the alias the same way and attach it in routes/api.php. Remember that API routes run the api group, not the web group, so session-based helpers like $request->user() need the right guard โ€” Sanctum for token-based APIs.

What is the difference between global middleware and group middleware? Global middleware runs on every request to the app. Group middleware runs only on routes in that group โ€” web for browser routes, api for API routes. A logging middleware is often global; a role check is usually an alias on specific routes.

Does the order of middleware matter? Yes. Middleware runs in the order it is listed, so auth must come before any middleware that reads $request->user(). The same applies inside bootstrap/app.php: append() adds to the end of the stack, prepend() to the start.

Can one middleware check several roles? Yes โ€” pass the role as a parameter, such as ->middleware('role:admin,editor'), and handle it as an extra argument in handle(). One class then covers every role instead of one class per role.

Was this helpful? 0 likes Login to like & bookmark
RH

Written by

Raja Hunain

Full Stack Developer at Raja Dev Solutions โ€” writes about real development work, the errors he faced and exactly how he fixed them, plus practical Laravel, PHP, JavaScript and MySQL tutorials.

More about the author

Comments (0)

No comments yet. Be the first to comment.

Leave a comment

Comments are moderated and appear after approval.

Keep reading

Related Articles

How to Upgrade Laravel 11 to Laravel 13 (Step by Step)
Tutorial Laravel Development 26 Nov 2026 ยท 8 min read

How to Upgrade Laravel 11 to Laravel 13 (Step by Step)

Laravel 11 reached end of life in March 2026, and Composer now refuses to install it at all. This tutorial walks you through upgrading a Laravel 11 project to Laravel 13 in two safe steps โ€” 11 to 12, then 12 to 13 โ€” including the PHP 8.3 requirement, the tinker conflict that blocks the second jump, and how to verify everything still works.