Block Specific IP Addresses Using Laravel 11 Middleware

Laravel sometimes needs to deal with specific ip addresses. Those ip address can be blocked to access application using laravel middleware functionality. Here we will explain how to enable this functionality in laravel application

Create Laravel Middleware

php artisan make:middleware BlockIpMiddleware
BlockIpController Middleware Class
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class BlockIpMiddleware
{
    
    protected $blockedIps = [
        '192.168.1.1',
        '203.0.113.5',
        // Add more IPs as needed
    ];

    
    public function handle(Request $request, Closure $next)
    {
        if (in_array($request->ip(), $this->blockedIps)) {
            abort(403);
        }

        return $next($request);
    }
}

Register Middleware in bootstrap/app.php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {		
	$middleware->alias([
            'blockip' => \App\Http\Middleware\BlockIpMiddleware::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Apply and Usage of Middleware in Controller

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class YourController extends Controller
{
    public function __construct()
    {
        $this->middleware('blockip');
    }

    // Your methods here
}

Apply and Usage in Routes

Route::middleware(['blockip'])->group(function () {
    Route::get('/your-route', [YourController::class, 'yourMethod']);
});

If any user tries to access to pages protected by blockip middleware, will get 403 access denied error

Tags: