How to Restrict/Block User Access from IP Address in Laravel

In this tutorial, I will implement a functionality to block user access using their public IP address by creating a middleware.

If you are searching for an example of Laravel to restrict/block user access from ip address then you are in the right tutorial. This tutorial goes into detail on Laravel restricting ip addresses to access users, here you will understand the concept of Laravel blacklist ip middleware.

Create a Middleware

        
        php artisan make:middleware BlockIpMiddleware
        
    

Edit the Middleware and past the below code:

        
        <?php

namespace App\Http\Middleware;

use Closure;

class BlockIpMiddleware
{
    public function handle($request, Closure $next)
    {
        // Define the array of blocked IP addresses
        $blockedIps = ['127.0.0.1', '192.168.1.1', '10.0.0.2'];

        // Get the client's IP address
        $clientIp = $request->ip();

        // Check if the client's IP matches any blocked IP
        if (in_array($clientIp, $blockedIps)) {
            // Optionally, you can log the blocked attempt or perform other actions

            // Return a response indicating that the request is blocked
            return response('Unauthorized', 401);
        }

        // Continue with the request if the IP is not blocked
        return $next($request);
    }
}
        
    

Related Post

Register the Middleware

Open the App\Http\Kernel.php file and add your middleware to the $routeMiddleware array:

        
        protected $routeMiddleware = [
    // ...
    'blockIp' => \App\Http\Middleware\BlockIpMiddleware::class,
];
        
    

Apply the Middleware:

        
        Route::get('/restricted-page', function () {
    // Your route logic here
})->middleware('blockIp');
        
    

Alternatively, you can apply the middleware to a route group:

        
        Route::middleware(['blockIp'])->group(function () {
    // Routes that should be protected by the middleware
    Route::get('/restricted-page', function () {
        // Your route logic here
    });
});
        
    

Leave a comment