Laravel: Simple Two-Factor Auth OTP via Email and SMS

These days, security is very important. That's why many applications implement two-factor authentication. In this tutorial, I will show you how to do that in Laravel, using Laravel Notifications and sending a one-time password via email or SMS.

Notice: there are more complicated 2FA methods like Google Authenticator, but in this tutorial I prefer the most simple and most widely used approach of email/SMS.

Prepare Laravel Application Back-End

For a quick authentication scaffold, we will use Laravel Breeze. Install it by running these two commands:

composer require laravel/breeze --dev
php artisan breeze:install

Next, we need to store our verification code somewhere. Also, we need to set its expiration time, so there's another DB field for this. So, add two fields to the default users migration:


public function up()
Schema::create('users', function (Blueprint $table) {
$table->string('two_factor_code')->nullable(); // [tl! add]
$table->dateTime('two_factor_expires_at')->nullable(); // [tl! add]

We also add those fields to app/Models/User.php properties $fillable array:

class User extends Authenticatable
protected $fillable = [
'two_factor_code', // [tl! add]
'two_factor_expires_at', // [tl! add]
// ...

Finally, for filling those fields let's create a method in the...

The full tutorial [11 mins, 2047 words] is only for Premium Members

Become a Premium Member for $129/year or $29/month

Written by

You might also like