Laravel Middleware: An Introduction

Posted April 24, 2019 in Blog, Laravel

In computer science a middleware is, as the name suggest, a piece of software in the middle:

Middleware is computer software that provides services to software applications beyond those available from the operating system.

https://en.wikipedia.org/wiki/Middleware

But Laravel isn’t an operating system, so what does this mean in Laravel? The term middleware is used here because it’s a piece of code that is run between the request and the process of the output. You can apply middleware to your routes, which will be run after the initial system is booted, but before the controller or similar called:

Laravel system => Middlewares => Your code

It is most commonly used with web and auth. Where web is in fact a group of middleware, but in short, it will enable common web utilities such as sessions and CSRF tokens. You can see the exact group here. auth is to guard your route from unauthorized users.

Another use case for a middleware you could try is an IP address block.
Finally, I will leave you with a simple example:

<?php

namespace App\Http\Middleware;

use Closure;

class IPFilterMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (getenv('REMOTE_ADDR') === 'xxx.xxx.xxx.xxx') {
            abort(403);
        }

        return $next($request);
    }
}

You could then add it to the group of web found in the earlier link.

In a real scenario, you would of course load the IPs from a database.

Leave a Reply

Your email address will not be published. Required fields are marked *