Middleware in Laravel

What is middleware in Laravel?

It is a mechanism to filter the HTTP request coming to your web application. For example you can use the middleware to authenticate user of the application. So you can check the request coming from the user has authentication to see the web page in your server before it is loading

To create a middleware you can use the following artisan command

IPFilter class is created at App\Http\Middleware

So I am adding following code to the handle function. This will check the IP of the request and send the Access Denied exception

Now you have to register your middleware to make it work.

Global Middleware

If you want your middleware to run for every http request you can register it globally. You can list the class in middleware array of the app/Http/Kernel.php

When you open any URL from the browser you will get the following screen

Assigning Middleware To Routes

You can assign the middleware to route as shown in the following code

in your routes\web.php file you can call the middleware