Skip to content

Laravel: How to implement Email verification on Signup

To configure your Laravel application for sending emails, you can update the MAIL_HOST value in your .env file. Here’s how you can do it:

1. Open your .env file in the root directory of your Laravel project.
2. Locate the following lines & modify the values according to your mail service configuration:

MAIL_MAILER=smtp
MAIL_HOST=YOUR_EMAIL_HOST
MAIL_PORT=587
MAIL_USERNAME=EMAIL_USERNAME
MAIL_PASSWORD=YOUR_PASSWORD
MAIL_ENCRYPTION=tls //ENCRYPTION USED BY YOUR EMAIL SERVICE PROVIDER

3. Locate the following & change it accordingly

APP_URL=http://your_app_url //i.e: http:itllive.com

4. Register the Middleware:
Register the Auth middleware EnsureEmailIsVerified in the $routeMiddleware array in the app/Http/Kernel.php file:

protected $routeMiddleware = [
    // Other middleware entries...
    'verified' => \App\Http\Middleware\EnsureEmailIsVerified::class,
];

5. Register the following routes in web.php

Route::get('/email/verify', [App\Http\Controllers\Auth\VerificationController::class, 'show'])->name('verification.notice');
Route::get('/email/verify/{id}/{hash}', [App\Http\Controllers\Auth\VerificationController::class, 'verify'])->middleware(['signed', 'throttle:6,1'])->name('verification.verify');
Route::post('/email/resend', [App\Http\Controllers\Auth\VerificationController::class, 'resend'])->middleware(['auth', 'throttle:6,1'])->name('verification.resend');

6. Apply the verified middleware to the routes or route groups that you want to protect. For example, you can apply it to all routes in the web.php routes file:

Route::middleware(['auth','verified'])->group(function () {
    // Your authenticated routes here...
});

7. Update Redirect Logic:
Ensure that after successful registration, users are redirected to a page where they are prompted to verify their email. You can customize the logic in your registration controller to redirect users accordingly.

For example, in your registration controller’s register method:

protected function registered(Request $request, $user)
    {
        if (!$user->hasVerifiedEmail() && !$request->user()) {
            return redirect('/email/verify');
        }

        return redirect($this->redirectPath());
    }

Leave a Reply

Your email address will not be published. Required fields are marked *