How to Ban IP Addresses in Laravel 12 Using Custom Middleware

Blocking malicious or unwanted traffic is a crucial aspect of web security. In Laravel 12, the most effective and elegant way to ban specific IP addresses is by implementing a custom route middleware.

This article guides you through the process, from creating the middleware to applying it to your application's routes.

Step 1: Generate the Middleware Class

We'll start by using the Laravel Artisan command to create the necessary middleware file. This command generates a class that intercepts HTTP requests before they reach your application logic.

php artisan make:middleware BlockIpMiddleware

This command creates a new file at app/Http/Middleware/BlockIpMiddleware.php.


Step 2: Implement the Ban Logic

Next, we need to modify the handle method within the BlockIpMiddleware.php file. This is where the core logic lives: it checks the incoming request's IP address against a defined list of banned IPs.

For simplicity, we define a static $blockedIps array directly in the class. For a production-level, scalable solution, you would typically fetch this list from a database or a configuration file.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class BlockIpMiddleware
{
    /**
     * Define the IP addresses to be blocked.
     *
     * @var array
     */
    protected $blockedIps = [
        '192.168.1.1',
        '10.0.0.5',
        // Add all IPs you wish to block here
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 1. Get the client's IP address from the request
        $clientIp = $request->ip();

        // 2. Check if the IP is on the blocked list
        if (in_array($clientIp, $this->blockedIps)) {
            
            // Optional: Log the attempt for auditing purposes
            \Log::warning("Blocked access attempt from blacklisted IP: {$clientIp}");
            
            // 3. Terminate the request with a 403 Forbidden response
            abort(403, 'Access to this resource is denied.');
        }

        return $next($request);
    }
}

Step 3: Register the Middleware Alias

For flexibility, we register the middleware as a route alias. This allows you to selectively apply the blocking logic to specific routes or route groups, instead of running it on every request.

Open the bootstrap/app.php file and locate the $middleware->alias section within the withMiddleware closure. Add your new middleware alias:

// In bootstrap/app.php
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            // Define a simple alias 'blockIp' for your middleware class
            'blockIp' => \App\Http\Middleware\BlockIpMiddleware::class,
        ]);
        // ... other middleware configurations
    })

Step 4: Apply the Middleware to Routes

The final step is to apply the 'blockIp' alias to the parts of your application you want to protect. You can do this in your route files (e.g., routes/web.php or routes/api.php).

A. Protecting a Group of Routes

This is the most common use case, securing an entire area like an Admin dashboard.

use Illuminate\Support\Facades\Route;

Route::middleware(['blockIp'])->group(function () {
    Route::get('/admin/dashboard', function () {
        return view('admin.dashboard');
    });
    Route::post('/admin/settings', function () {
        // ...
    });
});

B. Protecting a Single Route

If you only need to secure one specific endpoint:

Route::get('/sensitive-data', [SensitiveController::class, 'index'])->middleware('blockIp');

Any request originating from an IP address listed in your $blockedIps array will now be met with a 403 Forbidden status, effectively banning them from accessing the protected resources.


Conclusion: Implementing Robust Security

Using a custom middleware like the BlockIpMiddleware is a clean, native Laravel approach to implementing a robust IP ban list. By utilizing the framework's middleware stack, you ensure that malicious requests are stopped before they consume valuable application resources or hit your business logic.

While a static array is a great starting point for development, remember that for a production application, you should move the IP list to a more dynamic store like a database (MySQL/PostgreSQL) or a high-speed cache (Redis/Memcached). This allows your application to update the blacklist without requiring code deployments, making your security response instant and effective.

Copyright © 2025 Akhmad.dev