jabdefiant
jabdefiant

Reputation: 161

Laravel 5.7 - How can I dynamically trigger a user verification email?

When I register using the registration page, the link in the email that I get works fine.

When I instead use $user->sendEmailVerificationNotification() like I saw in vendor\laravel\framework\src\Illuminate\Auth\Listeners\SendEmailVerificationNotification.php, it does not work.

I get the email, but when I click on the verify link, I get redirected to the login page and the user does not get verified.

Use Case: My system has a superuser, who can add users, and I am hoping to fire that email for the users to verify themselves.

Any help would be appreciated.

Upvotes: 9

Views: 1386

Answers (1)

1000Nettles
1000Nettles

Reputation: 2334

This answer assumes you've already setup Laravel's Authentication and Email Verification.

When a user registers on the application, the controller by default is using the Illuminate\Foundation\Auth\RegistersUser trait. Notice the additional functionality that takes place in the register() method there, and also notice that a \Illuminate\Auth\Events\Registered event is generated which in turns triggers the listener SendEmailVerificationNotification (where you are currently getting your code from.)

For your custom class, you could potentially reuse the Illuminate\Foundation\Auth\RegistersUser trait on it, but that could feel strange as your class is probably not a controller and the trait involves extra controller-specific logic.

Instead, you could try ripping some code from Illuminate\Foundation\Auth\RegistersUser::register() and use it within your new class.

So, something similar to:

// If you do not yet have a new user object.
$user = \App\User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => \Illuminate\Support\Facades\Hash::make($data['password']),
]);

// Fire the event now with the user you want to receive an email.
event(new \Illuminate\Auth\Events\Registered($user));

More information:

Upvotes: 4

Related Questions