How to Implement Email Verification with Activation Code in Laravel | websolutioncode.com
How to Implement Email Verification with Activation Code in Laravel | websolutioncode.com

How to Implement Email Verification with Activation Code in Laravel

In web applications, it is crucial to ensure the security and validity of user email addresses. Email verification with activation codes is a common practice to confirm the authenticity of user-provided email addresses. In this tutorial, we will guide you through implementing email verification with activation codes in a Laravel application.

Prerequisites

Before we begin, make sure you have the following installed:

  1. Laravel Framework
  2. Composer (dependency manager for PHP)
  3. Mailtrap account (for testing emails)

Step 1: Create a new Laravel project

Open your terminal and run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel EmailVerification

Navigate to the newly created project directory:

cd EmailVerification

Step 2: Set up Database

Configure your database credentials in the .env file. Then, run the migration command to create the necessary tables for user management:

php artisan migrate

Step 3: Create User Model and Migration

Generate the User model along with the migration file using Artisan command:

php artisan make:model User -m

Open the generated migration file (database/migrations/yyyy_mm_dd_create_users_table.php) and modify the up method to include the necessary columns:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('activation_code')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

Run the migration again to apply the changes:

php artisan migrate

Step 4: Modify User Model

Open the User model (app/Models/User.php) and add the sendEmailVerificationNotification method:

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', 'activation_code',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function sendEmailVerificationNotification()
    {
        $this->notify(new \App\Notifications\VerifyEmail);
    }
}

Step 5: Create Email Verification Notification

Generate a new notification class using the following command:

php artisan make:notification VerifyEmail

This will create a new notification class at app/Notifications/VerifyEmail.php. Open this file and modify the toMail method to include the activation code:

public function toMail($notifiable)
{
    $url = url("/verify/{$notifiable->activation_code}");

    return (new MailMessage)
        ->line('Please click the button below to verify your email address.')
        ->action('Verify Email Address', $url)
        ->line('If you did not create an account, no further action is required.');
}

Step 6: Create Email Verification Route

Open the web.php file in the routes directory and add the following route:

Route::get('/verify/{activation_code}', 'App\Http\Controllers\Auth\VerificationController@verify')->name('verification.verify');

Step 7: Create Email Verification Controller

Generate a new controller for email verification:

php artisan make:controller Auth/VerificationController

Open the generated controller (app/Http/Controllers/Auth/VerificationController.php) and add the verify method:

use App\Models\User;

public function verify($activation_code)
{
    $user = User::where('activation_code', $activation_code)->first();

    if (!$user) {
        return redirect('/login')->with('error', 'Invalid activation code.');
    }

    $user->email_verified_at = now();
    $user->activation_code = null;
    $user->save();

    return redirect('/login')->with('success', 'Email verified successfully. You can now login.');
}

Step 8: Update User Registration Process

In your registration controller (app/Http/Controllers/Auth/RegisterController.php), override the registered method to send the email verification notification:

use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\RegistersUsers;

protected function registered(Request $request, $user)
{
    $user->sendEmailVerificationNotification();
    return redirect($this->redirectPath());
}

Step 9: Configure Email

Update your .env file with the necessary mail configuration, including your Mailtrap credentials:

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_mailtrap_username
MAIL_PASSWORD=your_mailtrap_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_verified_email_address
MAIL_FROM_NAME="${APP_NAME}"

Step 10: Test the Application

Run your Laravel development server:

php artisan serve

Visit http://localhost:8000/register in your browser, register a new user, and check your Mailtrap inbox for the email verification message.

Congratulations! You have successfully implemented email verification with activation codes in a Laravel application. This adds an extra layer of security to ensure that user-provided email addresses are valid and belong to the actual users.

Leave a Reply