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\ProtecrtedController@action’)->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*',
],

Autofix your Laravel application for free

Inspector is a Code Execution Monitoring tool specifically designed for software developers. You don’t need to install anything on the infrastructure, just install the Laravel package and you are ready to go.

If you are looking for effective automation, and the ability to automatically receive code change proposals to fix application errors try Inspector for free. Register your account.

Or learn more on the website: https://inspector.dev

Related Posts

Laravel Http Client Overview and Monitoring

Laravel HTTP client was introduced starting from version 10 of the framework, and then also made available in all previous versions. It stands out as a powerful tool for making HTTP requests and handling responses from external services. This article will delve into the technical foundations of the Laravel HTTP client, its motivations, and how

Laravel Form Request and Data Validation Tutorial

In this article I will talk about Laravel Form Request to send data from your application frontend to the backend. In web applications, data is usually sent via HTML forms: the data entered by the user into the browser is sent to the server and stored in the database eventually. Laravel makes it extremely simple

Upload File in Laravel

You can upload file in Laravel using its beautiful unified API to interact with many different types of storage systems, from local disk to remote object storage like S3. As many other Laravel components you can interact with the application filesystem through the Storage Facade: Illuminate/Support/Facades/Storage This class allows you to access storage drivers called