Block IP address from accessing Laravel application
KPK Dec 21st
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.
php artisan make:middleware RestrictIpMiddleware
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);