Laravel Middleware: An Introduction

In computer science a middleware is, as it 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.

- Wikipedia

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 code that is run between the request and the process of the output. You can apply a 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 un-authorised users.

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


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') === '') {

        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 IP's from a database.

In case you wonder. The cover was taken at Lennon Wall in Prague.

Expert in Laravel and Vue backed with MySQL databases. Independent developer who does freelance and love to travel. Feel free to drop me a message.

- Emil

Write your comment…

Be the first one to comment