@peterpan26 With middleware, like you’ve done so in the example above, and like you also did in your other thread asking about the exact same thing.
You should also have middleware do specific things. A middleware checking roles should not be doing authentication. That’s what the built-in auth middleware is for. You should “stack” your middleware to run one after the other. The auth middleware will redirect the user if they‘re not logged in. If they are authenticated, then your role middleware will run.
So, apply the middleware in order:
Route::middleware(['auth', 'role:administrator'])->group(function () {
// Administrator-only routes...
});
Your middleware should then only be concerned with checking if the authenticated user has the requested roles:
class EnsureUserHasRole
{
public function handle(Request $request, Closure $next, ...$roles)
{
$userRoles = $request->user()->roles()->pluck('role');
foreach ($roles as $role) {
if ($userRoles->contains($role)) {
return $next($request);
}
}
// If we are here, user does not have any of the requested role(s)
// Return a 403 Forbidden response since they are logged in but do not have permission
abort(403);
}
}