I'm trying to add a simple middleware to check if a user matches a role. I'm running into an issue when I use the middleware, I get an Exception:
ReflectionException: class role does not exist
I do not attempt to call a class named role so I assume this is happening magically in Laravel somewhere.
My middleware:
class RoleMiddleware
{
/**
* Run the request filter.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string $role
* @return mixed
*/
public function handle($request, Closure $next, $role)
{
if (! $request->user()->is($role)) {
return redirect('/login');
}
return $next($request);
}
}
In the users table, I have a role field and in the User model I have:
/**
* Check if a user is a certain role
*
* @param $role
* @return bool
*/
function is($role) {
return ($this->role == $role);
}
The route group:
Route::group(['prefix' => 'support', 'middleware' => ['role:admin', 'web']], function() {
Route::get('threads', 'ThreadController@index');
});
In Http/Kernel.php:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'role' => [
RoleMiddleware::class,
],
];
Anyone have any ideas on what could be causing this ReflectionException?
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,
],
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With