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
php artisan make:middleware IPFilter
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
public function handle($request, Closure $next) { if(request()->ip()=='127.0.0.1'){ abort(403, 'Access denied'); } return $next($request); }
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
protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, \App\Http\Middleware\IPFilter::class, ];
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
protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'ip' => \App\Http\Middleware\IPFilter::class, ];
in your routes\web.php file you can call the middleware
Route::get('admin/profile', function () { // })->middleware('ip');