Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Target class [role] does not exist in Laravel 11 Middleware Routes

I’m using Laravel 11 and I’m trying to implement middleware. It gives out the above error but I am very certain it does exist.

web.php

Route::get('/admin', [App\Http\Controllers\HomeController::class, 'dashboard'])
    ->middleware('role:admin')
    ->name('admin');

Kernel.php

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    protected $routeMiddleware = [
        'role' => \App\Http\Middleware\RoleMiddleware::class
        // Register your custom middleware here...
    ];

RoleMiddleware.php

class RoleMiddleware
{
    public function handle($request, Closure $next, $role)
    {   
        $user = Auth::user();
        if (!Auth::check() || !$user->hasRole($role)) {
            abort(403, 'Unauthorized');
        }
        return $next($request);
    }
}

As a side note, I made the Kernel.php manually, copying the full content from ChatGPT. It is placed in app\Http\Kernel.php. I’m not sure if that has something to do with the app not finding the ‘role’.

I’ve tried several method in web.php, which I think isn’t the problem. I’ve also tried changing the names to no avail. I don’t know how to move forward with this.

>Solution :

In Laravel 11 kernel.php has been removed. To register your custom middleware use app.php placed under the bootstrap directory.

->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'role' => \App\Http\Middleware\RoleMiddleware::class
        ]);
    })

For more ref please refer to Official docs

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading