php – Laravel Email Verification Disable & Enable with one touch-ThrowExceptions

Exception or error:

is there anyway we can set enable / disable email verification dynamically when users register ?

I think, in order to set email verification, we should set Auth::routes(['verify' => true]); and in User model, we should set class User extends Authenticatable implements MustVerifyEmail

Is there any simple way to do this dynamically?
So let’s say we set enable / disable in admin panel.
And according to it, can we set enable / disable in front auth page?

How to solve:

You can simply manipulate the email_verified_at column in the users table.

I suggest using an observer :

php artisan make:observer UserObserver --model=User

You can use config or database to determine whether to use verification email or not.

UserObserver

class UserObserver
{
    /**
     * Handle the user "created" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function created(User $user)
    {
        // Let's say you use config

        if (config('app.email_verification') == false) {
            $user->email_verified_at = now();
            $user->save();
        }
    }

    //

}

To determine email delivery, you can override sendEmailVerificationNotification in the User model :

/**
 * Send the email verification notification.
 *
 * @return void
 */
public function sendEmailVerificationNotification()
{
    if (config('app.email_verification')) {
        $this->notify(new VerifyEmail);
    }
}

Update

To keep email_verified_at as null, you can remove observer, then update your Auth::routes :

web.php

Auth::routes([
    'verify' => config('app.email_verification')
]);


Route::group([
    'middleware' => [config('app.email_verification') ? 'verified' : null]
], function () {

    // protected routes

    Route::get('dashboard', 'DashboardController@index');

});

Leave a Reply

Your email address will not be published. Required fields are marked *