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

aws sqs in a large scale laravel application inspector

AWS SQS in a large scale application

In today’s article, I’m going to show you how we use AWS SQS in our Laravel application, and how it helps us to manage 1.6 billion operations each month. In the image below you can see our typical bill for a month of AWS SQS usage: Before entering in the details of our system design

How to implement a reusable tooltip directive in Vuejs 3

Custom Tooltip Directive in Vuejs 3: Tutorial

Custom directives in Vuejs 3 are one of those things where there is no compatibility with the previous version of the framework.  Working on the new version of the Inspector frontend dashboard I had the need to show tooltips in many different points of the application. The goal was immediately to avoid duplicate code. Before

Why and how to create an Event Bus in Vuejs 3

Have you ever used an event bus in Vue 2 and don’t know how to recreate it in Vue 3? Since I’m working on the 2.0 version of my product’s UI (to be released in May) I’m publishing some technical tricks I learn migrating my application from Vuejs 2 to Vuejs 3. The current version