Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

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:

database/migrations/2014_10_12_000000_create_users_table.php:

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->string('two_factor_code')->nullable(); // [tl! add]
$table->dateTime('two_factor_expires_at')->nullable(); // [tl! add]
$table->timestamps();
});
}

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

class User extends Authenticatable
{
protected $fillable = [
'name',
'email',
'password',
'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, 2046 words] is only for Premium Members

Login Or Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses