My laravel 11 app give error "Target class [app\Http\Middleware\apiTokenMiddleware] does not exist." while it does. I make the middleware using php artisan make:middleware and put code on middleware :
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Models\ApiKey;
class apiTokenMiddleware
{
public function handle(Request $request, Closure $next): Response
{
$apiKey = $request->header('x-api-key');
if(!$apiKey || !ApiKey::where('key', $apiKey)->exists()){
return response()->json(['error' => 'Unauthorized'], 403);
}
return $next($request);
}
}
and i already register it on app.php like this :
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use app\Http\Middleware\apiTokenMiddleware;
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(['apiToken' => apiTokenMiddleware::class]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
then i try test it using router to call controller and then i got that error.
here the router Route::get('/api/test', [App\Http\Controllers\API\APITestController::class, 'test'])->middleware('apiToken');
Idk what im wrong with that, can you guys help?