Programmatically Block IP Addresses in Laravel 8/9/10

  • Last updated Apr 25, 2024

In this tutorial, we will learn how to programmatically block a user's IP address from accessing a Laravel website.

To block IP addresses in Laravel, do the following:

  1. Create a middleware named RestrictIpAddress in the app\Http\Middleware directory of your Laravel application by executing the following command in your terminal:
  2. php artisan make:middleware RestrictIpAddress
  3. After creating the RestrictIpAddress middleware file, paste the following code into 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, you need to register the middleware you just created in the app\Http\Kernel.php file within the $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, you will see the message "You are not authorized to access this site". in your browser: