I’m new to coding and I’m currently working on a project where I’m encountering an error that’s preventing me from moving forward. Note that I had to add the Kernel.php file manually because it did not install when I created my Laravel project.
I am working with Laravel 11.
I am getting the error: Target class [admin] does not exist.
Here is web.php :
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('back.dashboard');
})->middleware(['auth', 'verified', 'admin'])->name('dashboard');
Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});
Here is Kernel.php :
protected $middlewareAliases = [
'auth' => AppHttpMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'auth.session' => IlluminateSessionMiddlewareAuthenticateSession::class,
'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'password.confirm' => IlluminateAuthMiddlewareRequirePassword::class,
'precognitive' => IlluminateFoundationHttpMiddlewareHandlePrecognitiveRequests::class,
'signed' => AppHttpMiddlewareValidateSignature::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
'admin' => AppHttpMiddlewareAdmin::class,
'checkRole' => AppHttpMiddlewareCheckRole::class,
];
Here is the middleware Admin.php :
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use SymfonyComponentHttpFoundationResponse;
class Admin extends Middleware
{
/**
* Handle an incoming request.
*
* @param Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse) $next
*/
public function handle(Request $request, Closure $next): Response
{
$user = Auth::user();
if ($user && str_contains($user->role, 'admin')){
return $next($request);
}
abort(403, 'Accès non autorise');
}
}
I have checked the name to see if I might have misspelled it, and I have verified that the files are in the correct folders. Everything seems to be in order.
3
Answers
Try using different file name like ‘CheckAdminRole’. Thanks.
Remove extends Middleware from the Admin.php file.
Laravel 11 removed
Kernel.php
.You now have to register middleware through
bootstrap/app.php
https://laravel.com/docs/11.x/middleware#middleware-aliases