phplaraveljwtlaravel-middlewarelaravel-permission

laravel 11 Target class [role] does not exist ( spatie/laravel-permission)


i am developing REST API laravel 11 app i installed spatie/laravel-permission and i can create a user and assign role successfully also on login i can capture token and role successfully but when i to access route associate with role admin am getting error Target class [role] does not exist here is my api.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\UserController;

Route::middleware('auth:api')->group(function () {

    Route::middleware('role:admin')->group(function () {
        Route::apiResource('users', UserController::class); 
    }
}

and here is my user controller to get just users

use App\Models\User;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class UserController extends Controller
{
public function index()
    {
        $users = User::with('roles')->get();
        
        // Transform the response to include user details and their roles
        $response = $users->map(function ($user) {
            return [
                'id' => $user->id,
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'email' => $user->email,
                'phone_number' => $user->phone_number,
                'address' => $user->address,
                'roles' => $user->roles->pluck('name')
            ];
        });

        return response()->json($response);
    }
}

my user.php model

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements JWTSubject
{
    use HasFactory, Notifiable, HasRoles;

 ....
}

i tried to use in my api.php

use Spatie\Permission\Middlewares\RoleMiddleware;

Route::middleware('auth:api')->group(function () {

    Route::middleware([RoleMiddleware::class . ':admin'])->group(function () {
       Route::apiResource('users', UserController::class); 
    }
}

still didnot solve the problem. Also on laravel 11 no http/kernel.php


Solution

  • you can add the following line of code in the bootstrap/app.php and it should do the work.

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

    Remember to add use App\Http\Middleware\RoleMiddleware; in bootstrap/app.php