MasterPHP.in
Try Compiler →
Laravel Tutorial

Creating Custom Middleware in Laravel


In the last lesson you attached ready-made middleware like throttle to your routes. But your invoice app has needs that Laravel cannot guess. Only staff members should reach the invoice pages. And you want to know how long each page takes to respond, because the site runs on a small EC2 server and you want to catch slow pages early.

You could put this code in every controller method, but you already know where that road leads. Middleware is the right place, and Laravel makes it easy to write your own.

In this lesson you will create two custom middleware: one that runs before the controller and stops outsiders, and one that runs after the controller and adds information to the response. You will also see how to attach them to routes.

 

Creating a Middleware Class

Use Artisan to generate the class, just as you did for controllers:

php artisan make:middleware EnsureStaffIsLoggedIn

Laravel confirms with a message like this:

INFO  Middleware [app/Http/Middleware/EnsureStaffIsLoggedIn.php] created successfully.

Open the new file. It contains a class with one method, and that method simply passes the request along:

<?php

namespace App\Http\Middleware;

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

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

The naming habit is to describe the rule, like EnsureStaffIsLoggedIn or EnsureInvoiceIsUnpaid, so the name reads like a sentence when you see it on a route.

 

Understanding the handle() Method

Every middleware has a handle() method, and Laravel calls it for each request that passes through. It receives two things:

  • $request is the current request, the same object you used in the Request Object lesson
  • $next is a function that represents the rest of the journey, which means the next middleware and finally your controller

Calling $next($request) means “pass this request on, and give me the response that comes back”. The method must always return a response, either one it creates itself or the one it receives from $next.

public function handle(Request $request, Closure $next): Response
{
    // 1. Code here runs BEFORE the controller

    $response = $next($request);

    // 2. Code here runs AFTER the controller

    return $response;
}

This small shape is the whole idea of middleware. Everything you write goes either before or after the $next($request) line.

 

A Before Middleware: Stopping Outsiders

Let us write the staff check. It uses the session from the Sessions & Cookies lesson. If there is no staff_id stored, the middleware stops the request. Otherwise it passes the request on:

public function handle(Request $request, Closure $next): Response
{
    if (! $request->session()->has('staff_id')) {
        abort(403, 'This area is for staff only.');
    }

    return $next($request);
}

When the check fails, abort(403) ends the request with a “Forbidden” page, and the controller never runs. When it passes, the request continues as normal.

Request  -->  EnsureStaffIsLoggedIn
                 |
        staff_id in session?
          |               |
         no              yes
          |               |
     403 Forbidden    $next($request)  -->  Controller

This hand-made check is only a teaching tool. In the Authentication chapter you will replace it with Laravel’s real login system and the auth middleware. The shape of the code, however, will look just like this.

 

Attaching Your Middleware to Routes

In modern Laravel you do not register anything to start using a middleware. Any class in app/Http/Middleware can be attached by its class name. Import it in routes/web.php and use it in a group, as you learned in the last lesson:

use App\Http\Middleware\EnsureStaffIsLoggedIn;

Route::middleware([EnsureStaffIsLoggedIn::class])->group(function () {
    Route::get('/invoices/summary', InvoiceSummary::class)
        ->name('invoices.summary');

    Route::resource('invoices', InvoiceController::class);
});

Using the class name works, but it is long. In the next lesson you will give the middleware a short alias like staff, so your routes read ->middleware('staff').

 

Testing It

To try the middleware, add a temporary route outside the protected group. It stores a staff_id in the session and sends you to the invoice list:

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

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

Now test the full flow:

http://localhost:8000/invoices           -->  403, this area is for staff only
http://localhost:8000/demo/staff-login   -->  redirects to /invoices
http://localhost:8000/invoices           -->  works, because the session has staff_id

Delete the demo route when you are finished. A real login page will replace it later.

&nbsp;

An After Middleware: Adding Information to the Response

A middleware can also do its work after the controller. Create one that measures how long the request took, and adds that time to a response header:

php artisan make:middleware AddResponseTimeHeader


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

    $response = $next($request);

    $milliseconds = round((microtime(true) - $start) * 1000);
    $response->headers->set('X-Response-Time', $milliseconds . 'ms');

    return $response;
}

Here the order matters. The timer starts first, then $next($request) runs the controller and everything after it, and only then does the middleware calculate the time and add the header. The $response variable always holds a real response object. Even when your controller returns an array or a view, Laravel has already turned it into a response before the middleware sees it.

Attach it to the same group, next to the first middleware:

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

To see the header, open the browser developer tools, go to the Network tab and click the request. Or use curl in the terminal:

curl -i http://localhost:8000/invoices

You will find a line like this in the response headers:

X-Response-Time: 12ms

&nbsp;

Changing the Request Before It Arrives

A before middleware can also adjust the request instead of stopping it. Suppose a user can ask for ?per_page=100000 and make your server load every invoice at once. A small middleware can cap the value, using the merge() method from the Request Object lesson:

public function handle(Request $request, Closure $next): Response
{
    $request->merge([
        'per_page' => min($request->integer('per_page', 10), 100),
    ]);

    return $next($request);
}

The controller then reads per_page as usual, and it can never be more than 100. One middleware protects every route it is attached to.

&nbsp;

Middleware or Controller?

Not every check belongs in middleware. Here is a simple guide:

  • Use middleware when the same rule applies to many routes, such as staff-only access, limits or headers
  • Use the controller or a service when the rule belongs to one action, such as “this invoice cannot be edited after it is paid”
  • Use middleware for the web request itself, and a service class for business rules
  • If you copy the same few lines into three controllers, that is a hint to move them into a middleware

 

Common Mistakes

Mistake 1: Forgetting to Return the Response

public function handle(Request $request, Closure $next): Response
{
    $response = $next($request);

    $response->headers->set('X-Response-Time', '12ms');
}

The method must return a response. Without a return, PHP stops with:

TypeError: App\Http\Middleware\AddResponseTimeHeader::handle(): Return value must be of type Symfony\Component\HttpFoundation\Response, none returned

Add return $response; at the end.

 

Mistake 2: Forgetting return Before redirect()

if (! $request->session()->has('staff_id')) {
    redirect('/staff/login');
}

return $next($request);

The redirect is created but never returned, so the code continues to $next($request) and the controller runs anyway. The visitor sees the protected page, and no error warns you. Always write return redirect(...). The abort() function is safer here, because it stops the request by itself.

 

Mistake 3: Importing the Wrong Response Class

If you import Illuminate\Http\Response instead of the Symfony class from the generated stub, a redirect breaks the return type:

TypeError: Return value must be of type Illuminate\Http\Response, Illuminate\Http\RedirectResponse returned

Keep the use Symfony\Component\HttpFoundation\Response; line that Artisan generated. It works for every kind of response.

 

Mistake 4: Forgetting to Import the Middleware in Routes

Route::middleware([EnsureStaffIsLoggedIn::class])->group(function () {
    // ...
});

Without the use App\Http\Middleware\EnsureStaffIsLoggedIn; line in routes/web.php, Laravel cannot find the class:

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

Add the import at the top of the file.

 

Mistake 5: Using the Session Before It Has Started

The session is started by the StartSession middleware, which belongs to the web group. If your middleware runs earlier than that, for example if you add it as global middleware, reading the session fails with:

RuntimeException: Session store not set on request.

Attach session-dependent middleware to routes inside routes/web.php, as in this lesson, so the session is ready.

 

Mistake 6: Creating a Redirect Loop

If the staff middleware redirects strangers to /staff/login, and the login page is inside the same protected group, the browser is sent to the login page, which redirects to the login page again. The browser gives up with ERR_TOO_MANY_REDIRECTS. Keep the login page outside the protected group.

&nbsp;

Quick Summary

  • Create a middleware with php artisan make:middleware EnsureStaffIsLoggedIn. The file appears in app/Http/Middleware.
  • Its handle() method receives the $request and a $next function, and must return a response.
  • Code before $next($request) runs before the controller, and code after it runs after the controller.
  • A before middleware can stop the request with abort() or return redirect(...), or it can change the request.
  • An after middleware receives the response from $next($request), can change it, and must return it.
  • Attach a middleware by its class name with ->middleware([MyMiddleware::class]), or to a group of routes.
  • You do not need to register a middleware just to use its class name in a route.
  • Put access rules, limits and headers in middleware, and keep business logic in services.
  • Always return redirects and responses, or the request continues or the method fails.
  • Do not put the login page inside the group that requires login.

 

What’s Next

Your two middleware work, but typing the full class name on every route is tiring, and you may want a middleware that accepts settings, such as the number of requests allowed or the role required. In the next lesson, Middleware Aliases, Groups & Parameters (bootstrap/app.php), you will give your middleware short names, add them to the global and web groups, and pass parameters to them.

Frequently Asked Questions

They are stored in the app/Http/Middleware folder, and Artisan puts new ones there automatically when you run make:middleware. The namespace is App\Http\Middleware. You can create subfolders if you want to group them, as long as the namespace matches the folder.
Not to start using it. You can attach any middleware class to a route with its class name, and there is no Kernel file to edit in modern Laravel. Registration in bootstrap/app.php is only needed for short aliases, groups and global middleware.
It passes the request to the next step, which is the next middleware or the controller, and returns the response that comes back. Code before this line runs before the controller. Code after it runs after the controller.
Store the result of next(next(request) in a variable, then use or change the response, and return it at the end. Because the response already exists at that point, you can add headers or record information about the request.
Yes. A middleware can return any response, including response()->json with a status code such as 403. This is common for API routes, where a redirect to a login page makes no sense.

Share this tutorial