Laravel Force User to Verify Email After Registration

Published on April 16, 2021 1 min read

Hi artisans! In this article, I’ll show how we can force user to verify email address after registration. Let’s get started:

Table of Contents

  1. Install Laravel and Basic Config
  2. Email SMTP Configuration
  3. Implement MustVerifyEmail Contract
  4. Update Auth Routes
  5. Use Verified Middleware

Install Laravel and Basic Config

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Email SMTP Configuration

Open .env file and set your SMTP credentials. You can use Mailtrap for testing purpose.

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your-username
MAIL_PASSWORD=your-password
MAIL_ENCRYPTION=tls

Implement MustVerifyEmail Contract

In this step, we’ll implement the MustVerifyEmail contract in the User model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

We need to check one thing. Open user table migration file from database/migrations folder and check this line:

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable(); // add if doesn't exists
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Update Auth Routes

Open routes/web.php and update auth routes like:

// before
Auth::routes();

// after
Auth::routes(['verify' => true]);

Use Verified Middleware

We can allow verified users to visit routes like:

Route::get('/profile', [UserController::class, 'profile'])->middleware('verified');

We can also restricted access to UserController like:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class UserController extends Controller
{

    public function __construct()
    {
        $this->middleware(['auth','verified']);
    }
  
    public function profile()
    {
        return "Welcome to your profile";
    }
} 
That’s all. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow