arkanrosyid's avatar

My laravel 11 app give error "Target class [app\Http\Middleware\apiTokenMiddleware] does not exist."

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?

0 likes
3 replies
tykus's avatar
tykus
Best Answer
Level 104

You are not being sufficiently careful about the casing for your classes, files and directories; *nix are case-sensitive. To fix this issue, you need to properly alias the FQCN for the middleware:

use App\Http\Middleware\apiTokenMiddleware;

More generally, convention dictates that classes (and their associated files) have an uppercase first letter, i.e.

// app/Http/Middleware/ApiTokenMiddleware.php
namespace App\Http\Middleware;

class ApiTokenMiddleware
{
    // etc.

https://www.php-fig.org/psr/psr-12/

2 likes
olavea's avatar

My api call works now because of your answer. Thanks a bunch @tykus !

💪🥳🏴‍☠️

Please or to participate in this conversation.