# 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](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 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](https://github.com/laravel/laravel/blob/master/app/Http/Kernel.php). `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:

```
<?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](https://github.com/laravel/laravel/blob/master/app/Http/Kernel.php).

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.*
