I'm trying to block certain IP addresses from accessing my website using laravel 11.3.0, all the solutions i.m coming across suggest the method were you register the middleware in kernel.php but the version of laravel i'm using does not have kernel.php. So how do i go about this?
i have tried registering it in 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->web(append: [
\App\Http\Middleware\HandleInertiaRequests::class,
\Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
]);
$middleware->alias([
'role' => \Spatie\Permission\Middleware\RoleMiddleware::class,
'permission' => \Spatie\Permission\Middleware\PermissionMiddleware::class,
'role_or_permission' => \Spatie\Permission\Middleware\RoleOrPermissionMiddleware::class,
]);
return $middleware;
})
->withMiddleware([
\App\Http\Middleware\BlockIpMiddleware::class,
])
->withExceptions(function (Exceptions $exceptions) {
//
})
->create();
ERROR PHP Fatal error: Uncaught TypeError: Illuminate\Foundation\Configuration\ApplicationBuilder::withMiddleware(): Argument #1 ($callback) must be of type ?callable, array given, called in C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\bootstrap\app.php on line 29 and defined in C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\vendor\laravel\framework\src\Illuminate\Foundation\Configuration\ApplicationBuilder.php:227 Stack trace: #0 C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\bootstrap\app.php(29): Illuminate\Foundation\Configuration\ApplicationBuilder->withMiddleware(Array) #1 C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\artisan(12): require_once('C:\xampp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\swamsite2\Swarmsite\Daniel\telegram\vendor\laravel\framework\src\Illuminate\Foundation\Configuration\ApplicationBuilder.php on line 227
Laravel 11 provides for the separation of the api and web middleware groups. For my use case, what I did was something similar to this:
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
$middleware->web(prepend: [
\App\Http\Middleware\EncryptCookies::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\BlockIpMiddleware::class,
]);
$middleware->api(append: [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class . ':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\BlockIpMiddleware::class,
]);
})->create();