braed
1 year ago
440
6
Laravel

Prevent Login Before Email Verification

Posted 1 year ago by braed

I would like to prevent my users from logging in without having first verified their email address by clicking the link (via the functionality added with Laravel 5.7).

Currently I have added overrode authenticated() in my LoginController and RegisterController with a call to a function like so:

protected function requireEmailVerfication(Request $request, $user, $redirectTo)
    {
        if (!isset($user->email_verified_at)) {
            Auth::logout();
            
            return redirect('/login')
                ->withErrors([
                    'email' => 'Please verify your email address by clicking the link in the email we sent.<br>'
                        . 'If you did not receive an email, <a href="' . '/email/verify' . '">click here to resend</a>.',
                ])->withInput();
        }
        
        return redirect($redirectTo);
    }

For some reason, this is now preventing the user from being email verified - I click the email link and I get redirected to the login page but the user hasn't been verified in the database. Also, logging the user in and then logging the user back out if they aren't email verified seems awfully backwards and inefficient. Can someone tell me a proper way to do this? Thanks!

Please sign in or create an account to participate in this conversation.