Email verification laravel

Email verification in Laravel!

Laravel provides a built-in feature for email verification, which allows you to verify the email address of a user before allowing them to access their account. Here's a step-by-step guide on how to implement email verification in Laravel:

Step 1: Enable Email Verification

In your Laravel project, open the config/auth.php file and set the email_verification option to true:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
        'email_verification' => true,
    ],
],

Step 2: Create a Verification Table

Laravel requires a verification table to store the verification tokens. Run the following command to create the table:

php artisan migrate

This will create a verification_tokens table in your database.

Step 3: Send Verification Email

When a user signs up, Laravel will send a verification email to their registered email address. You can customize the email template by creating a new file in the resources/views/emails directory, e.g., verify-email.blade.php.

In this file, you can add the verification token and a link to verify the email address:

@component('mail::message')
# Verify Your Email Address

You are receiving this email because you requested to verify your email address.

Please click the link below to verify your email address:

<a href="{{ $token }}">Verify Email Address</a>

If you did not request to verify your email address, please ignore this email.

Best regards,
{{ config('app.name') }}
@endcomponent

Step 4: Verify Email Address

When a user clicks the verification link, Laravel will verify their email address. You can create a new route to handle the verification request:

Route::get('/verify-email/{token}', 'VerificationController@verify');

In the VerificationController, you can verify the token and update the user's email address:

public function verify(Request $request, $token)
{
    $user = User::whereEmail($request->user()->email)->first();
    if (!$user ||! Hash::check($token, $user->email_verification_token)) {
        return redirect()->route('login')->withErrors(['email' => 'Invalid verification token']);
    }

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

    return redirect()->route('home')->with('success', 'Email address verified successfully!');
}

Step 5: Update User Model

In your User model, you need to add the emailVerificationToken method to generate the verification token:

public function emailVerificationToken()
{
    return Str::random(60);
}

Step 6: Update User Table

In your users table, add a new column to store the verification token:

$table->string('email_verification_token')->nullable();

That's it! With these steps, you've implemented email verification in your Laravel application.

Remember to update your config/auth.php file to set email_verification to true and create a verification table in your database.