Programmatically Block IP Addresses in Laravel 8/9

In this tutorial, we will show you how to programmatically block a user IP address from accessing a Laravel website.

To block IP addresses in Laravel 8/9, do the following:

  1. Create RestrictIpAddress.php middleware file at app\Http\Middleware\ of your Laravel application using the following command on your terminal:
  2. 
    php artisan make:middleware RestrictIpAddress
    
  3. After the RestrictIpAddress.php gets created, copy the following code to the file:
  4. 
    <?php
    
    namespace App\Http\Middleware;
    use App\Http\Util\RemoteUser;
    use Illuminate\Support\Facades\Log;
    use Closure;
    
    class RestrictIpAddress
    {
        // add ip addresses to block
        public $restrictIpAddrs = ['127.0.0.1', 'ip2', 'ip3', 'ip4'];
    
        
        public function handle($request, Closure $next)
        {
            $remoteUserIP = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
            
            if (in_array($remoteUserIP, $this->restrictIpAddrs)) {
                //use this incase you want to show the attacker a custom message
                //return response()->json(['message' => "You are not authorized to access this site."]);
                
                //make invalid redirect using double forward slash so that attacker is redirected to unknown error
                return Redirect::to('//error');
            }
    
            return $next($request);
        }
    }
    
  5. Next, we need to register the above middleware that we just created at app\Http\Kernel.php in $middlewareGroups array as shown in the example below:
  6. 
    protected $middlewareGroups = [
            'web' => [
                //other middlewares
                \App\Http\Middleware\RestrictIpAddress::class,
            ],
    
            'api' => [
                'throttle:api',
                //middlewares
            ],
        ];
    
  7. Run and test your application. If you visit your website from the restricted IP address then you will see "You are not authorized to access this site." message on your browser: