Home > Mobile >  Optional Email Verification in Laravel
Optional Email Verification in Laravel

Time:12-05

How can I make the email verification optional in Laravel? I have a routes that can be accessed as guest. However, I want all authenticated user to be email verified whenever they access any part of the website including those pages that can be access as guest.

If I'm going to add middleware('verified') on all routes, guest needs to login to access those public pages.

Example:

Route / or /posts/1 can be access as a guest. However, if the user is logged in, I want them to be email verified first to access it.

CodePudding user response:

The EnsureEmailIsVerified (verified) middleware checks to see if the User is authenticated which is why it won't work for guest users.

You could create a new middleware class called something like EnsureEmailIsVerifiedUnlessGuest (or whatever you want):

public function handle($request, Closure $next, $redirectToRoute = null)
{
    if ( $request->user() &&
        ($request->user() instanceof MustVerifyEmail &&
        ! $request->user()->hasVerifiedEmail())) {
        return $request->expectsJson()
                ? abort(403, 'Your email address is not verified.')
                : Redirect::guest(URL::route($redirectToRoute ?: 'verification.notice'));
    }

    return $next($request);
}

Then add it to the $routeMiddleware array in your app/Http/Kernel.php file:

'verified-or-guest' => \App\Http\Middleware\EnsureEmailIsVerifiedUnlessGuest::class,

Then you can use it with your routes with

->middleware('verified-or-guest')
  • Related