Block IP address from accessing Laravel application

Block IP address using Laravel

Block IP address from accessing Laravel application

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.

  1. Create a Middleware “RestrictIpMiddleware.php”.
  2. Paste the code inside handle function.
  3. Register the middleware in kernel function.
  4. 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);

KPK

K PradeepKumar - Founder & CEO of KPK Technology