Table of Contents
Introduction:
HTTP requests filter middleware in Laravel is a middleware that filters requests based on certain conditions before they are passed to the controller. This is useful for tasks such as rate limiting, IP blocking, or other types of access control. Here is an example of how you can create a HTTP requests filter middleware in Laravel:
Create a new middleware:
First, you need to create a new middleware using the following command:
php artisan make:middleware RequestFilterMiddleware
This will create a new middleware class in the app/Http/Middleware directory.
Define the filter conditions:
In the handle method of the middleware class, you can define the conditions that the request must meet in order to be passed to the controller. For example, you can use the Request facade to check the IP address of the request and block it if it’s from a certain range:
use Illuminate\Http\Request;
public function handle(Request $request, Closure $next)
{
$ip = $request->ip();
if (strpos($ip, '192.168.') === 0) {
return response('Unauthorized.', 401);
}
return $next($request);
}
Register the middleware:
Next, you need to register the middleware in the app/Http/Kernel.php file. You can register it as a global middleware or a route middleware depending on your needs.
Apply the middleware:
Finally, you can apply the middleware to the routes or controllers that need it. For example, if you want to apply it to all routes, you can use the middleware method on the Route facade:
Route::middleware(RequestFilterMiddleware::class)->group(function () {
Route::get('/', 'HomeController@index');
Route::get('/about', 'HomeController@about');
});
In this example, the RequestFilterMiddleware will be applied to all routes in the group, and the filter conditions defined in the middleware will be checked before the request is passed to the controller. If the request’s IP address starts with “192.168.”, the request will be blocked and a 401 Unauthorized response will be returned.
Summary:
This is just a basic example of how you can create a HTTP requests filter middleware in Laravel. You can customize it to suit your needs by adding more filter conditions, changing the response, or adding other functionality.
Must Read: What is middle Middleware and how to use Middleware in Laravel Framework?