The issue is that the middleware is being applied to the password reset routes as well, which causes an endless loop of redirects. To fix this, you can modify the shouldExcludeRoute method to exclude the password reset routes as well:
private function shouldExcludeRoute($request)
{
$passwordRoutes = [
'nova.pages.password.email',
'nova.pages.password.reset',
'nova.password.email',
'nova.password.reset'
];
return in_array($request->route()->getName(), $passwordRoutes) || Str::startsWith($request->route()->getName(), 'password.');
}
This will exclude any route that starts with password. in addition to the existing password reset routes.
Alternatively, you can modify the middleware to only apply to specific routes instead of all routes:
public function handle(Request $request, Closure $next): Response
{
$user = auth()->user();
if ($user && $user->passwordChangedAt === null && !$this->shouldExcludeRoute($request)) {
return redirect()->route('nova.pages.password.email');
}
return $next($request);
}
private function shouldExcludeRoute($request)
{
$passwordRoutes = [
'nova.pages.password.email',
'nova.pages.password.reset',
'nova.password.email',
'nova.password.reset'
];
return in_array($request->route()->getName(), $passwordRoutes);
}
Then, you can apply the middleware only to the routes that need it:
Route::middleware(['forcePasswordReset'])->group(function () {
// Routes that require password reset
});