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
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.
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