To solve the issue with the role middleware in Laravel 11, you need to ensure that the middleware is properly registered and implemented. Here’s a step-by-step guide to help you set up role-based middleware in Laravel 11:
-
Create the Middleware: First, create a middleware that will handle the role checking. You can do this using the Artisan command:
php artisan make:middleware RoleMiddleware -
Implement the Middleware: Open the newly created middleware file located at
app/Http/Middleware/RoleMiddleware.phpand implement the logic to check the user's role.<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class RoleMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string $role * @return mixed */ public function handle(Request $request, Closure $next, $role) { if (!Auth::check() || Auth::user()->role !== $role) { // Optionally, you can redirect to a specific page or return a 403 response abort(403, 'Unauthorized action.'); } return $next($request); } } -
Register the Middleware: Next, you need to register the middleware in your
app/Http/Kernel.phpfile. Add it to the$routeMiddlewarearray:protected $routeMiddleware = [ // Other middleware 'role' => \App\Http\Middleware\RoleMiddleware::class, ]; -
Apply the Middleware to Routes: Now you can apply the middleware to your routes. Update your route definition to use the
rolemiddleware:use App\Http\Controllers\ListingController; Route::get('/approvals', [ListingController::class, 'show'])->middleware('role:super-admin'); -
Ensure User Model Has Role Attribute: Make sure your
Usermodel has aroleattribute. This could be a column in youruserstable. For example:// In your User model (app/Models/User.php) class User extends Authenticatable { // Other model properties and methods public function getRoleAttribute() { return $this->attributes['role']; } } -
Database Migration: If you don't already have a
rolecolumn in youruserstable, you need to add it. Create a migration to add therolecolumn:php artisan make:migration add_role_to_users_table --table=usersThen, update the migration file:
public function up() { Schema::table('users', function (Blueprint $table) { $table->string('role')->after('email')->default('user'); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('role'); }); }Run the migration:
php artisan migrate
By following these steps, you should be able to implement and use role-based middleware in your Laravel 11 application without encountering the "Target class [role] does not exist." error.