In many cases we need to block some particular IP address from accessing our website content or application. We can restrict IP in Laravel through a simple piece of code.
How to block or restrict any IP address from accessing your Laravel application ? lets see. We can create a Middleware to check the blocked IP address and redirect to the page we want.
- Create a Middleware “RestrictIpMiddleware.php”.
- Paste the code inside handle function.
- Register the middleware in kernel function.
- Add the registered middleware in routes in order to restrict the access.
Creating a Middleware
php artisan make:middleware RestrictIpMiddleware
The Code
Paste the below code in the handle function of the middleware
$restricted_ip = "Comma seperated IP address which is to be restricted";
$ipsDeny = explode(',',preg_replace('/\s+/', '', $restricted_ip));
if(count($ipsDeny) >= 1 )
{
if(in_array(request()->ip(), $ipsDeny))
{
\Log::warning("Unauthorized access, IP address was => ".request()->ip);
return response()->json(['Unauthorized!'],400);
}
}
return $next($request);