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*',
],

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

Create a query for histogram charts with MySQL – Tutorial

To create a statistical query to build a histogram chart with MySQL, you can use the COUNT() function along with GROUP BY to count occurrences of values within a specified range or category created by the grouping constraint.  Especially for time series data there are a lot of use cases for histograms like monitoring the

Try the new Google Chat notification channel

Hi, I’m happy to announce that Google Chat is now available as a notification channel for your application. Now you can receive all important notifications of what happens in your application in your Google Chat environment in real time. Inspector Notification Channels allow you to create an automated and  informed workplace, helping your collaborators to

AI content creation to help you improve the Developer Experience

Co-founders are the first people in the trenches for any start-up, taking the idea and turning it into a sustainable business that can really make other people’s life better. In these early years of Inspector I have never told about my co-founders thanks to whom I was able to spend all my time building the