Laravel 5.7 - Verification email is not sent
Asked Answered
B

7

7

I've upgraded my laravel instance from version 5.6 to version 5.7. Now I try to use the built-in email verification from laravel.

My problem is that I don't get an email after successful registration when I use the "resend" function the email arrives.

What is the problem?

Bertrando answered 29/9, 2018 at 14:44 Comment(5)
Would you mind sharing your code with us? It would be extremely helpful.Diagnostician
I'ts the default code after setting up laravel and the implepented authentification/verification stuff.Bertrando
did you follow all the step to configure email verification?Ceilometer
are you receiving email on spam folder or inbox ?Ase
No. When I resend the mail everything works fine.Bertrando
B
8

If you have a custom registration page, you could just fire the event after you have created the user like so:

event(new Registered($user));

Boni answered 25/11, 2018 at 20:59 Comment(1)
this is the only answer that worked for me. In case anyone comes across this in the future, you have to include this in the top of your controller use Illuminate\Auth\Events\RegisteredPrevention
H
28

I had this exactly same problem. That is default code from Laravel.

In order to send the email after successful registration you can do this workaround:

at App\Http\Controllers\Auth\RegisterController

change this:

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }

to this:

protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        $user->sendEmailVerificationNotification();

        return $user;
    }
Harriette answered 20/10, 2018 at 15:51 Comment(6)
i did as shown above but i still can't get the email in my inbox i checked mailtrap and it shows that the mail was sent !!Neuroma
If you use mailtrap you will never receive the email at your own inbox. All data will be at mailtrap. Thats a tool for development.Harriette
what should i use to get email in my own inbox ?Neuroma
@YoussefBoudaya Laravel provides a clean, simple API over the popular SwiftMailer library with drivers for SMTP, Mailgun, SparkPost, Amazon SES, and sendmail. I recommend you to start using SMTP by only defining the credentials at your .env file. Here a example: MAIL_DRIVER=smtp MAIL_HOST=smtp.gmail.com MAIL_PORT=465 [email protected] MAIL_PASSWORD=123456 MAIL_ENCRYPTION=sslHarriette
I found out that the "proper (5.7 default) way" to this is, to go App\Providers\EventServiceProvider class and add the listener for SendEmailVerificationNotification. Add it like this: protected $listen = [ Illuminate\Auth\Events\Registered::class => [ Illuminate\Auth\Listeners\SendEmailVerificationNotification::class, ], ]; *You can use/import the classes to make things pretty.Philanthropist
There's already an event for Registered and a listener SendEmailVerificationNotification. Confused why this is the accepted answer. Isn't there a better way? I'm having this issue.Byington
C
16

I also have had the same issue. As I checked the source code, it isn't necessary to implement to call the sendEmailVerificationNotfication() method, you just should add the event handler to your EventServiceProvider.php, as because of your event handler was previously created, so Larael can't update that. It should look like this:

namespace App\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];
Cootie answered 24/10, 2018 at 8:13 Comment(1)
Following the Laravel structure, this should be the correct answer, thanks a lot.Whoso
B
8

If you have a custom registration page, you could just fire the event after you have created the user like so:

event(new Registered($user));

Boni answered 25/11, 2018 at 20:59 Comment(1)
this is the only answer that worked for me. In case anyone comes across this in the future, you have to include this in the top of your controller use Illuminate\Auth\Events\RegisteredPrevention
R
5

in case somebody else is looking for a solution for the same problem.

please read the documentation, it explains exactly what needs to be done to solve this issue

https://laravel.com/docs/5.7/verification

in a nutshell, and if you are already using 5.7 (i.e you have the necessary fields in your users table) all that you need to do is the following:

  • make your User model implement the MustVerifyEmail interface.
  • add ['verify' => true] to the Auth::routes method Auth::routes(['verify' => true]);

you can find everything you need about email verification in the link above.

Romish answered 7/2, 2019 at 10:4 Comment(0)
M
2

In addition to djug's reply, if you experience the same problem after upgrading from version 5.6, just as I did, you'll find step-by-step guide what to implement here:

https://laravel.com/docs/5.7/upgrade

under the section Email Verification

Hope this helps someone as I was struggling quite some time with this.

Malm answered 14/3, 2019 at 19:29 Comment(0)
S
1

I know this post is a bit on the older side but I had a similar issue with Laravel 7. I think Zane's answer above should be the accepted answer. Just to elaborate on that use the following steps. This should be done after installing the auth scaffolding with composer and php artisan. Note: I am by no means a Laravel pro. If there are any issues with my code PLEASE let me know. The more I learn the better I can be.

Prepare the User Model


Ensure your App\User model implements Illuminate\Contracts\Auth\MustVerifyEmail:

<?php

namespace App;

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

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    // ...
}

Setup Routes


In routes\web.php change this:

Auth::routes();

To this:

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

After that you can specify which routes need a verified email address by either using middleware directly on a route like this:

Route::get('/profile','ProfileController@index')->middleware('verified');

or you can do it in the controller's constructor function like this:

public function __construct()
{
    $this->middleware(['auth','verified']);
}

Modified Register Controller


I'm using the following register controller code. Note the register function contains a call to the following:

event(new Registered($user));

This was the key to getting the initial registration email to send.

Register Controller

Keep in mind this controller was designed to work with a primarily ajax site, thus why the register function returns a json response.

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Auth;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'phone_number' => ['required', 'numeric', 'min:10'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'password_confirmation'=> ['required', 'string'],
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        $user=User::create([
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'phone_number' => $data['phone_number'],
            'password' => Hash::make($data['password']),
        ]);
        return $user;
    }

     /**
     * Execute registration and login the user
     *
     * @param  array  $request
     * @return response
     */
    public function register(Request $request)  {
        $validation = $this->validator($request->all());
        if ($validation->fails())  {
            return response()->json($validation->errors(),422);
        }
        else{
            $user = $this->create($request->all());
            event(new Registered($user));
            Auth::login($user);
            if (Auth::user()){
                return response()->json(['success'=>'Registration Successful']);
            }
        }
    }
}
Spindry answered 15/7, 2021 at 2:1 Comment(1)
Yeah, that seems right. For me dispatching a new register event seems better than sending the verification email as in the current accepted answer. I think I will accept the answer from Zane. But thanks anyway for this nice clarification :)Bertrando
T
-1

Make sure you have your From Email setup as most SMTP servers won't allow sending from any address. The env config for those are:

[email protected]
MAIL_FROM_NAME=Something
Tiebout answered 25/4, 2020 at 17:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.