Laravel RoleMiddleware, class role not found

For Spatie/Laravel-Permissions to work properly we have to register the two route middleware (role and permission) in app/Http/Kernel.php as follows, along with the other two auth middleware:

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
    'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
];

In Http/Kernel.php, you need to include the full path to RoleMiddleware. E.g.:

...
'role' => [
    \App\Http\Middleware\RoleMiddleware::class,
],
...

Try to change this

Route::group(['prefix' => 'support', 'middleware' => ['role:admin', 'web']], function() {
    Route::get('threads', 'ThreadController@index');
});

to

Route::group(['prefix' => 'support', 'middlewareGroups' => ['role:admin', 'web']], function() {
    Route::get('threads', 'ThreadController@index');
});

I'm a beginner in laravel i was facing this same problem and fixed by changing the name from middleware to "your-own-middelware-name".


This came down to two problems:

  1. $middlewareGroups may not allow for parameters. (Needs to be confirmed) Dropping RoleMiddleware down to $routeMiddleware got rid of the exception.

  2. Having 'web' after 'role:admin' resulted in a null $request->user(). So for future users, you may need to consider placement of your middleware and a check to see if $request->user() is null.

Hope this helps someone else.