Block route by IP address in Laravel

- - Laravel
SHARE THIS ARTICLE

In Laravel, using middleware, you can block access to a specific route by IP address. Middleware allows you to filter HTTP requests entering your application. Here’s how you can do it step by step:


Step 1: Create a Middleware

Run the following Artisan command to create a new middleware:

php artisan make:middleware IPBlockerMiddleware

This will create a new middleware file in app/Http/Middleware/IPBlockerMiddleware.php.


Step 2: Implement IP Blocking Logic

Open the newly created middleware file (IPBlockerpMiddleware.php) and add the logic to block specific IP addresses.

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class IPBlockerMiddleware
{
    // List of blocked IP addresses
    private $blockedIPs = [
        '192.168.1.100', // Example IP to block
        '192.168.1.101', // Another example IP
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Get the client's IP address
        $clientIP = $request->ip();

        // Check if the client's IP is in the blocked list
        if (in_array($clientIP, $this->blockedIPs)) {
            // Return a 403 Forbidden response
            return response('Access Denied', 403);
        }

        // Allow the request to proceed
        return $next($request);
    }
}

Step 3: Register the Middleware

Next, register your middleware in app/Http/Kernel.php. Add it to the $routeMiddleware array:

protected $routeMiddleware = [
    // Other middleware
    'block.ip' => \App\Http\Middleware\IPBlockerMiddleware::class,
];

Step 4: Apply the Middleware to Routes

Now, apply the middleware to the routes you want to protect. You can do this in your routes/web.php or routes/api.php file.

Example: Block IP for a Specific Route

Route::get('/protected-route', function () {
    return 'This route is protected!';
})->middleware('block.ip');

Example: Block IP for a Group of Routes

Route::middleware('block.ip')->group(function () {
    Route::get('/protected-route-1', function () {
        return 'This route is protected!';
    });

    Route::get('/protected-route-2', function () {
        return 'This route is also protected!';
    });
});

Step 5: Test the Middleware

  1. Access the protected route from a blocked IP address. You should see a 403 Forbidden response.

  2. Access the route from an allowed IP address. You should see the route’s content.


Optional: Dynamically Load Blocked IPs

If you want to load the blocked IPs dynamically (e.g., from a database or configuration file), you can modify the middleware to fetch the IPs from a source.

Example: Load Blocked IPs from Config

  1. Add the blocked IPs to your config/app.php file:

     
    'blocked_ips' => [
        '192.168.1.100',
        '192.168.1.101',
    ],
  2. Update the middleware to use the config:

     
    private $blockedIPs;
    
    public function __construct()
    {
        $this->blockedIPs = config('app.blocked_ips');
    }

Optional: Use a Package

If you prefer a pre-built solution, you can use a package like spatie/laravel-ip to manage IP blocking.

Post Tags:
Join the Newsletter

Sign up for our personalized daily newsletter

Kodesmart

#1 GUIDE TO DRUPAL, WORDPRESS, CSS AND CUSTOM CODING | BEGINNER TO PRO