In this tutorial, we’ll demonstrate how to implement IP-based access restrictions in a Laravel 12 application. By creating custom middleware, we can effectively block or allow users based on their IP addresses.
IP restrictions are particularly valuable for:
- Protecting sensitive or confidential information
- Limiting access to specific geographic regions
- Preventing unauthorized access to admin areas
- Complying with security regulations
Implementation Overview
We’ll create a BlockIpMiddleware that checks incoming requests against a blacklist of IP addresses. This middleware can then be applied to routes, controllers, or route groups as needed.
Prerequisites
- Laravel 12 installation
- Basic knowledge of Laravel middleware
Step-by-Step Implementation
Step 1: Install Laravel 12
Begin by creating a new Laravel project:
composer create-project laravel/laravel example-app
Step 2: Create the Middleware
Generate the middleware using Artisan:
php artisan make:middleware BlockIpMiddleware
Edit the newly created file at app/Http/Middleware/BlockIpMiddleware.php:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class BlockIpMiddleware
{
// List of restricted IP addresses
public $blockIps = ['192.168.1.1', '10.0.0.1', '127.0.0.1'];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next): Response
{
if (in_array($request->ip(), $this->blockIps)) {
abort(403, "Access denied. Your IP address is restricted.");
}
return $next($request);
}
}
Step 3: Register the Middleware
Register the middleware alias in bootstrap/app.php:
<?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();
Step 4: Apply the Middleware
Apply the middleware to your routes in routes/web.php:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\RSSFeedController;
Route::middleware(['blockIP'])->group(function () {
Route::resource('users', UserController::class);
Route::resource('rss', RSSFeedController::class);
});
Step 5: Test the Application
Start the development server:
php artisan serve
Visit http://localhost:8000/users in your browser to test the implementation.
