Laravel IP based restricition

Submitted by decipher - 6 years ago

How to disable any ip from accessing your laravel app? Here is the solution. 1) Create Middleware "IPRestrictMiddleware". 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.

 $restricted_ip = "192.168.1.104"; // add IP's by comma separated
 $ipsDeny = explode(',',preg_replace('/\s+/', '', $restricted_ip));
 if(count($ipsDeny) >= 1 )
 {
    if(in_array(request()->ip(), $ipsDeny))
    {
        \Log::warning("Unauthorized access for api, IP address was => ".request()->ip);
         return response()->json(['Unauthorized!'],400);
    }
 }
 return $next($request);