How to Create An OTP In Laravel

This time we will discuss how to create OTP code in PHP or more precisely using the Laravel framework.

How to create an OTP in Laravel

How to create an OTP in Laravel

What is an OTP code?

OTP code is an abbreviation ofOne Time-Passwordcode or can also be interpreted as apasswordcode that is only temporary and can be used only once. Because this OTP code can only be used once, usually this OTP code has an expiration date.

One Time-Passwordcodes are generally used as one-timepasswordsintended for carrying out verification and authentication processes. It can also be used to improve the security of systems created as a second layer apart from using general passwords.

This OTP code is usually sent via SMS, Online Chatting App such as WA/Telegram or to an email address.

Flow security with OTP

There are many OTP implementation flows, but this time I will try to make a very simple flow so that friends understand the OTP concept better.

The flow is:

  1. User registers and fills in the required user data
  2. After the user successfully registers, redirect to the OTP validation page
  3. Send OTP to user’s email
  4. user fills in the OTP code
  5. The system validates the OTP code
  6. activate the user and log in the user.

So the flow is very simple, right? So apart from being able to be used to verify whether the user’s email is active or not, this OTP code can also be further developed by creating a second layer of security when logging in.

Laravel installation

We have learned the flow, it’s time to install Laravel first.

Maybe you already have a Laravel application that is running, you can use the application that has been built. So, for those who haven’t been able to, try installing Laravel first.

I will just install it quickly directly with the composer commandcomposer create-project laravel/laravel otp-sample

After the installation is complete, go to the folderotp-sampleor other folders that you created.

Install Package Brezze

We will use the breeze package from Laravel directly to take care of authentication matters. So we don’t create from 0 anymore. Check more details at: https://github.com/laravel/breeze

We will slightly modify the implementation of the OTP code when registering.

To install breeze, run the following command.

composer require laravel/breeze --dev

Once installed, run the next command.

php artisan breeze:install

In this tutorial, I will only use the blade template, you can try using react/vue according to the frontend you want.

So, after we have installed Laravel and Brezze, next try running PHP Artisan Serve to see the Laravel project in our browser.

Openhttp://localhost:8000

Update .ENV dan Migrate

Almost forgot, so since we’re going to send an email, I’ll set it upMAIL_MAILER=logfor testing email later.

Don’t forget to also setup the database according to your database.

Don’t forget to repeat itphp artisan serveto refresh the settings.

Create tables and models for OTP User

To create an otp table, we will first create a migration with a command like the following:

php artisan make:migration create_user_otps

Once created, open the migration file and adjust the contents of the file as follows:

We will create a tableuser_otpsthat will accommodate the OTP data with the fields, namely:

  1. id
  2. user_id: for relations to the user table
  3. otp_code: otp code, where the number is 6 letters long.
  4. expired_at: datetime, so that the OTP code cannot be used again if the expiration date has passed.

If so, run migration by running the command:php artisan migrate

Next is to create a UserOTP model with the commandphp artisan make:model UserOTP

Open the fileUserOTP.phpand adjust its contents as follows:

The next step is to add the activeOTP relationship in the user model.

Open the User.php model file and add the following relations:

Now that the model and database are ready, it’s time to create a flow for the OTP.

Modification of Controller Registers

By default, when submitting a register, the file used isRegisteredUserController.phpspecifically the methodstore()

Now open the fileRegisteredUserController.php, we will make a few changes in the methodstore()

So when registering, we will create an OTP code which will be sent to the user’s email.

We need to change the verification flow for emails sent via eventsRegistered().

Create a Listener and Notification file to Send OTP

We will create 2 files for the listener and notification sending an OTP code to the user’s email.

Run these 2 commands to create these 2 files.

php artisan make:listener SendOTPEventListener

php artisan make:notification SendOTPNotification

Open the fileSendOTPEventNotification.phpand update its contents as below:

This file will be responsible for sending an email to the user containing the OTP code later.

Open the fileSendOTPEventListener.phpand update its contents as below:

The next step is that we need to change the listener when the Registered event is called.

Open the fileEventServiceProvider.phpand edit the listen section to look like this:

So the story is that when there is an eventRegistered, the app will call the listenerSendOTPEventListenerto send an email notification to the user.

This kind of design is usually referred to asan event driven pattern.

Create an OTP page display

Do you still remember the previous flow?

So when you have finished filling in the registration data, we will redirect to the page to fill in the OTP code.

Create a new route andviewto display the OTP code validation form.

Open the fileweb.phpand add thisroute:

Next, create a newviewwith a nameotp-verification.blade.php

Don’t forget to create another new route to handle post data and check whether the OTP code is valid or not.

Open the file againweb.phpand add this new route:

Okay, all processes for validation have been completed

It looks more or less like the following.

Now is the time to try it, OK?

Please register and if successful you will be redirected to the OTP code page.

You can check the OTP code at laravel.log to fill in the email.

If you have successfully filled in the OTP code, the user will be automatically verified and immediately log in to the system.

How to validate OTP?

The OTP that we make is very simple. The concept is to replace verification via link with an OTP code.

So when verifying the OTP code, if the OTP code is correct, then we update the fieldemail_verified_atto the data at that time.

This means that the user has successfully verified their data correctly.

Conclusion

So that’s how to make a simple implementation of OTP code in Laravel. Actually, there are several use cases that can be developed further, for example how to handle when the OTP token expires.

It can also be developed as additional security for user login, where apart from logging in with a password, you also need to fill in the OTP code when logging in.

Maybe later I will add several other use cases in the continuing article about how to create an OTP code with Laravel.

Leave a Reply

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