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
What is an OTP code?
OTP code is an abbreviation of One Time-Password code or can also be interpreted as a password code 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-Password codes are generally used as one-time passwords intended 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:
- User registers and fills in the required user data
- After the user successfully registers, redirect to the OTP validation page
- Send OTP to user’s email
- user fills in the OTP code
- The system validates the OTP code
- 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.
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 command
composer create-project laravel/laravel otp-sample
After the installation is complete, go to the folder
otp-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.
Update .ENV dan Migrate
Almost forgot, so since we’re going to send an email, I’ll set it up
MAIL_MAILER=log for testing email later.
Don’t forget to also setup the database according to your database.
Don’t forget to repeat it
php 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 table
user_otpsthat will accommodate the OTP data with the fields, namely:
- user_id: for relations to the user table
- otp_code: otp code, where the number is 6 letters long.
- 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 command
php artisan make:model UserOTP
Open the file
UserOTP.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 is
RegisteredUserController.phpspecifically the method
Now open the file
RegisteredUserController.php, we will make a few changes in the method
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 events
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 file
SendOTPEventNotification.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 file
SendOTPEventListener.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 file
EventServiceProvider.phpand edit the listen section to look like this:
So the story is that when there is an event
Registered, the app will call the listener
SendOTPEventListenerto send an email notification to the user.
This kind of design is usually referred to as an 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 and view to display the OTP code validation form.
Open the file
web.phpand add this route :
Next, create a new view with a name
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 again
web.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 field
email_verified_atto the data at that time.
This means that the user has successfully verified their data correctly.
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.