composer require ipinfo/ipinfo -W
php artisan make:middleware CheckIPRestricted
app/Http/Middleware/CheckIPRestricted.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use ipinfo\ipinfo\IPinfo;
use Symfony\Component\HttpFoundation\Response;
class CheckIPRestricted
{
public function handle(Request $request, Closure $next): Response
{
$client = new IPinfo('TheToken');
$details = $client->getDetails($request->ip());
if ($details->country_name && $details->country != 'TheCountryCode') {
abort(403);
}
return $next($request);
}
}
bootstrap/app.php
<?php
use App\Http\Middleware\CheckIPRestricted;
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->append(CheckIPRestricted::class);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();