What is Middleware in laravel

Middleware provides a convenient mechanism for filtering HTTP requests entering your website. Laravel includes a middleware that verifies the user of your website is authenticated.

There are many middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All middleware are located in the app/Http/Middleware directory.

Defining Middleware

To create a new middleware in Laravel use the make:middleware Artisan command.

php artisan make:middleware CheckAge

This command will create a new CheckAge class within your app/Http/Middleware directory. This middleware we allow access to the route if the supplied age is greater than 200. Otherwise we redirect the users back to the home URI.


namespace App\Http\Middleware;

use Closure;

class CheckAge
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
        if ($request->age <= 200) {
            return redirect('home');

        return $next($request);

As you can see if the given age is less than or equal to 200 middleware will return an HTTP redirect to the client otherwise the request will be passed further into the website. To pass the request deeper into the website call the $next callback with the $request.

It's to envision middleware as a series of layers HTTP requests must pass through before they hit your application. Each layer can examine request and even reject entirely.