简体   繁体   中英

How to send confirmation mail to new email address in Laravel?

I have a form that can change current email address of a user. I want when user changes his current email address to a new email address to automatically sends confirmation mail to this new email address where user would confirm that email. How can that be done? Here is my code. Any help is appreciated.

UserProfileController.php

public function changeEmailAddress(UpdateEmailRequest $request)
{
    if ($request->new_email != $request->repeat_email)
        return response()->json(['status' => 'Emails do not match.'], 404);

    if ($request->new_email == $request->user()->email)
        return response()->json(['status' => 'Email cannot be the same as old email'], 404);

    if(sizeof(User::where('email','=',$request->new_email)->get()) > 0)
        return response()->json(['status' => 'Email already exists'], 404);

    $request->user()->email = $request->new_email;
    $request->user()->email_verified_at = null;
    $request->user()->save();

    return response()->json(['status' => 'success'], 200);
}

index.blade.php

<section data-edit="email" class="editEmail">
    <form action="{{ route('user.update.email') }}" method="POST" class="flex">
        @method('PATCH')
        @csrf
        <div class="form-group">
            <input type="text" placeholder="New Email Adress" name="new_email">
        </div>
        <div class="form-group">
            <input type="text" placeholder="Repeat Email Adress" name="repeat_email">
        </div>
        <div class="form-group">
            <button class="submit">BUTTON</button>
        </div>
    </form>
</section>

web.php

Route::patch('/profile/change-email', 'UserProfileController@changeEmailAddress')- 
 >name('user.update.email');

UpdateEmailRequest.php

public function rules()
{
    return [
        'email' => ['string', 'email', 'max:255', 'unique:users,email'],
    ];
 }

To laravel 5.7+ implements MustVerifyEmail in your App\Models\User or App\User

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

and in app/routes/web.php

Add such routes as email/verify and email/resend to the app:

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

and simple in your method just call this:

$user->sendEmailVerificationNotification();

Short answer:

All you should have to do is call event(new \Illuminate\Auth\Events\Registered($user));

If that doesn't work, there may be a few things you need to set up first (see Longer Answer).

Longer answer:

There are a few things you need in order to add backend support for user email verification.

First step is making sure your User model implements the proper methods:

// app/User.php:
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail {
    // this provides:
    //  ->markEmailAsVerified(),
    //  ->hasVerifiedEmail(): bool
    //  ->sendEmailVerificationNotification()
    use \Illuminate\Auth\MustVerifyEmail;

There's a nice built-in event you can then use to fire off an email to users once they register. You can trigger this manually or as part of a model listener (not discussed here). This needs to be registered in your event listeners first, though. See Laravel's Event guide for more information.

// app/Providers/EventServiceProvider.php:
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider {

    protected $listen = [
        // ...
        'Illuminate\Auth\Events\Registered' => [
            'Illuminate\Auth\Listeners\SendEmailVerificationNotification',
        ],

Once those two things are in place, triggering the verification email can be done anywhere in your application:

// fire off the Registered event, so that new users get a verification email
event(new \Illuminate\Auth\Events\Registered($user));

This will only work if the event listener is in place, and User has the right hierarchy.

The event handler ( SendEmailVerificationNotification ) checks if $user is a MustVerifyEmail that's not already verified, and if it is, it calls $user->sendEmailVerificationNotification which fires off an instance of \Illuminate\Auth\Notifications\VerifyEmail .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM