How to create custom middleware in Laravel

Valerio Barbera

In this article I will show you how Laravel Middlewares work like a filtering pipeline to process http requests before they come into the controller.

I’m Valerio, software engineer and CTO at Inspector, a Laravel package that works with middleware to monitor what your application is doing HTTP traffic in real-time in your Laravel application.

What is middleware?

A middleware is a class to pass HTTP requests through. These classes can be concatenated and organized to create custom filtering paths of HTTP requests flowing into your application.

Here is a simplified schema of how the middleware system works inside a Laravel application.

They are a layer that acts in the middle between the reception of the http request in the web server and the controller.

Laravel already ships with a ton of default configured middleware out of the box if you check in the app/Http/Middleware directory.

All of the default middlewares and custom ones must be registered in the app/Http/Kernel.php file before being used. The Kernel class is also the place where you have to register your own custom middleware.

Steps for creating Custom Middleware in Laravel Application

The following PHP artisan command can be used to create middleware files, so launch your terminal (or command prompt on Windows) and go to your application directory, then type the following command:

php artisan make:middleware SecretHeaders

This command will create a new SecretHeaders.php file in the app/Http/Middleware directory.

namespace App\Http\Middleware;
use Closure;
class SecretHeaders 
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Your code here...
        return $next($request);
    }
}

The middleware must include logic to process the HTTP request. In this instance, our validation criteria are to see if the request has some headers needed to allow it to go through.

Let’s use the following script to create logic to verify the secret header:

class SecretHeaders 
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!is_null($request->header('x-secret-key', null))) {
			return $next($request);
		}
        abort(401);
    }
}

In the logic above, the request will be rejected if it doesn’t contain the “x-secret-key” header.In order to use the middleware we must register it in the app/Http/Kernel.php file in the $routeMiddleware section:

protected $routeMiddleware = [
    ...,
    'verify.secret’ => \App\Http\Middleware\SecretHeaders::class,
];

Now you can add this restriction to specific routes so that only authorized requests can access the endpoints.

Route::get(‘/api/protected-endpoint’, App\Http\Controllers\[email protected]’)->middleware(['auth', 'verify.secret']);

How to use Inspector middleware to monitor your Http traffic

Inspector library for Laravel applications ships with a pre-packaged middleware that allows you to observe what happens inside your application during HTTP requests fulfillment.

First install the Inspector package with the command below:

composer require inspector-apm/inspector-laravel

Then you need to configure an ingestion key in your environment file. Get a new ingestion key creating a new project in your Inspector account.

INSPECTOR_INGESTION_KEY=xxxxxxxxxxxxxxxxxxxxxxx

Now you can attach the Inspector middleware in the app/Http/Kernel.php file:

/**
 * The application's route middleware groups.
 *
 * @var  array
 */
protected $middlewareGroups = [
    'web' => [
        ...,
        \Inspector\Laravel\Middleware\WebRequestMonitoring::class,
    ],
    'api' => [
        ...,
        \Inspector\Laravel\Middleware\WebRequestMonitoring::class,
    ]
];

Attaching the middleware to the predefined “web” and “api” middleware groups you will probably be able to monitor the entire application.

Learn more about http request monitoring in the official Inspector documentation: https://docs.inspector.dev/guides/laravel/http-requests-monitoring

Ignore Http Requests

Sometimes it could be needed to turn off monitoring on specific urls. Think about paths like /nova, /telescope, or other parts of your app that don’t affect the user experience.

First you need to publish the Inspector configuration file using the command below:

php artisan vendor:publish --provider="Inspector\Laravel\InspectorServiceProvider"

Add the urls you don’t want to monitor in the “ignore_url” configuration parameter. You can also use the wildcard character “*” to exclude all sub-paths.

/*
 |---------------------------------------------------------------------
 | Web request url to ignore
 |---------------------------------------------------------------------
 |
 | Add at this list the url schemes that you don't want monitoring
 | in your Inspector dashboard. You can also use wildcard expression (*).
 |
 */
 
'ignore_url' => [
    'telescope*',
    'vendor/telescope*',
    'horizon*',
    'vendor/horizon*',
],

Interested in adding Inspector to your tech stack?

Create your account here. You can try Inspector for free as long as you want.

Inspector is a Code Execution Monitoring tool that helps you to identify bugs and bottlenecks in your applications automatically. Before your customers do.

It is completely code-driven. You won’t have to install anything at the server level or make complex configurations in your cloud infrastructure.

Create an account, or visit our website for more information: https://inspector.dev/laravel

Related Posts

How to make Vite Hot Module Replacement work on Windows

As many of our community members already know, we recently started the renovation of the Inspector dashboard UI with a fresh new design and a modern technology stack. In this article I will explain why we decided to leave Webpack and embrace Vite as assets build tool and Hot Module Replacement. I will show you

Http traffic monitoring for Slim framework

This article follows the release of the first version of the monitoring library for Slim framework. Thanks to this package you can fully monitor the HTTP traffic against your application based on Slim. It takes less than one minute to get started. First let me give you a bit of context. Introducing the Slim framework

How to use wildcards in ExpressJs and Fastify monitoring libraries

With the booming software economy, the demand for new applications and software-defined automations is set to grow in the future years. Companies in any industry are creating software in the form of internal business tools, productivity tools, integrations, automations, and more. As a result, there is a need for tools that make it easy to

How to build scalable applications

Get the e-book about the Inspector scalability journey.