Share this:

Step-by-Step Guide on How to Implement Laravel Login with Mobile Number OTP

Introduction

In this tutorial, we will walk through the process of implementing login with mobile number OTP in a Laravel app. This approach to authentication adds an extra layer of security by requiring users to enter a one-time passcode sent via SMS in addition to their username and password.

To follow along with this tutorial, you should have basic knowledge of Laravel and be familiar with PHP and HTML. We will start by setting up a new Laravel project and installing any necessary dependencies, then move on to setting up the database and implementing the OTP generation and sending process. Next, we will create the login form and handle OTP verification, and finally wrap up with a conclusion and suggestions for further reading. So, let’s get started!

Prerequisites:

  • Basic knowledge of Laravel: This tutorial assumes that you have a basic understanding of how to work with Laravel and are comfortable creating routes, controllers, and blade templates.
  • Familiarity with PHP and HTML: You should have a basic understanding of how to write PHP code and how to create HTML forms.
  • Composer: You will need to have Composer installed on your system in order to install the necessary dependencies for this tutorial.
  • Twilio account: You will need to have a Twilio account and have purchased a phone number in order to send SMS messages containing the OTP.
  • Local development environment: You will need to have a local development environment set up in order to follow along with this tutorial. This can be a LAMP or LEMP stack, or you can use a virtual machine or containerization tool such as Vagrant or Docker.

Setting up the Laravel project

To get started, you will need to create a new Laravel project. If you have the Laravel installer installed on your system, you can create a new project by running the following command in your terminal:

laravel new projectname

Replace “projectname” with the desired name for your project. This will create a new Laravel project in a directory with the specified name.

Next, you will need to install any necessary dependencies. For this tutorial, we will be using the Twilio SDK to send SMS messages containing the OTP. To install the Twilio SDK, you can use Composer by running the following command in your terminal:

composer require twilio/sdk

Once the dependency is installed, you will need to configure your Twilio account details in the .env file located in the root of your Laravel project. You will need to add your Twilio Account SID, Auth Token, and the phone number you have purchased from Twilio as the TWILIO_PHONE_NUMBER value.

TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=your_twilio_phone_number

With the project set up and dependencies installed, you are now ready to proceed to the next step of setting up the database.

Also Read : Integrating Social Media Share Buttons with Laravel

Setting up the database

To set up the database for our Laravel app, we will first need to create a migration for the user table. This can be done using the following artisan command:

php artisan make:migration create_users_table

This will create a new migration file in the database/migrations directory. In the up() method of the migration, we will need to add a phone field to the user table. Your migration file should look something like this:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('phone')->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

Next, we can run the migration to create the user table in the database:

php artisan migrate

Once the migration has been run, we can seed the database with some test users using a seed class. In the run() method of the seed class, you can add some test user records to the database like this:

User::create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => bcrypt('password'),
    'phone' => '+1234567890'
]);

User::create([
    'name' => 'Jane Doe',
    'email' => 'jane@example.com',
    'password' => bcrypt('password'),
    'phone' => '+1234567891'
]);

Finally, you can run the seed class to insert the test users into the database:

php artisan db:seed

With the database set up and seeded with test data, you are now ready to proceed to the next step of implementing OTP generation and sending.

Implementing OTP generation and sending

To implement the login form, we will first need to create a blade template for the form. You can create a new blade template in the resources/views directory and give it a name such as login.blade.php.

In the template, you can create a form using standard HTML like this:

<form method="POST" action="/login">
    @csrf

    <label for="phone">Phone</label>
    <input type="text" name="phone" id="phone" required>

    <button type="submit">Send OTP</button>
</form>

This form has a single input field for the user’s phone number and a submit button to send the OTP.

Next, we will need to create a route and controller action to handle the form submission. In your routes file (e.g. routes/web.php), you can add a route like this:

Route::post('/login', 'AuthController@login');

Then, in your AuthController you can create the login() action to handle the form submission:

public function login(Request $request)
{
    // Validate the phone number
    $validatedData = $request->validate([
        'phone' => 'required|regex:/^\+[0-9]{10,12}$/|exists:users'
    ]);

    // Look up the user with the given phone number
    $user = User::where('phone', $request->phone)->first();

    // If the user is found, generate and send the OTP
    if ($user) {
        // Generate the OTP
        $otp = rand(10000, 99999);

        // Store the OTP in the session
        $request->session()->put('otp', $otp);

        // Send the OTP via SMS using the Twilio SDK
        // (configure your Twilio account details in the .env file)
        $twilio = new Client(env('TWILIO_ACCOUNT_SID'), env('TWILIO_AUTH_TOKEN'));
        $twilio->messages
            ->create($request->phone, [
                'from' => env('TWILIO_PHONE_NUMBER'),
                'body' => "Your OTP is $otp"
            ]);

        // Redirect to the OTP verification form
        return redirect('/verify-otp');
    } else {
        // If the phone number is not found in the database, display an error message
        return back()->withErrors(['phone' => 'Phone number not found']);
    }
}

This action first validates the phone number to ensure that it is in the correct format and exists in the database. If the phone number is valid, it looks up the user with the given phone number and generates a random OTP. The OTP is then stored in the session and sent to the user via SMS using the Twilio SDK. Finally, the user is redirected to the OTP verification form. If the phone number is not found in the database, an error message is displayed to the user.

With the login form and handling logic in place, we can now move on to implementing OTP verification.

Implementing OTP verification

To implement OTP verification, we will need to create a route and controller action to handle the form submission. In your routes file (e.g. routes/web.php), you can add a route like this:

Route::post('/verify-otp', 'AuthController@verifyOtp');

Then, in your AuthController you can create the verifyOtp() action to handle the form submission:

public function verifyOtp(Request $request)
{
    // Validate the OTP
    $validatedData = $request->validate([
        'otp' => 'required|digits:5'
    ]);

    // Get the OTP from the session
    $otp = $request->session()->get('otp');

    // Check if the entered OTP is correct
    if ($request->otp == $otp) {
        // If the OTP is correct, log the user in and redirect to the dashboard
        auth()->loginUsingId(1); // replace 1 with the user's actual ID
        return redirect('/dashboard');
    } else {
        // If the OTP is incorrect, display an error message
        return back()->withErrors(['otp' => 'Incorrect OTP']);
    }
}

This action first validates the OTP to ensure that it is a 5-digit number. It then retrieves the OTP from the session and checks if it matches the one entered by the user. If the OTP is correct, the user is logged in and redirected to the dashboard. If the OTP is incorrect, an error message is displayed to the user.

With OTP verification in place, we have now successfully implemented login with mobile number OTP in our Laravel app. In the next step, we will wrap up with a conclusion and suggestions for further reading.

Conclusion

In this tutorial, we walked through the process of implementing login with mobile number OTP in a Laravel app. We started by setting up the Laravel project and installing any necessary dependencies, then moved on to setting up the database and implementing the OTP generation and sending process. We also created the login form and handled OTP verification.

To summarize, the steps we took were:

  1. Set up the Laravel project and install dependencies.
  2. Set up the database by creating a migration for the user table, adding a ‘phone’ field, and seeding the database with test users.
  3. Implement OTP generation and sending by creating a route and controller action, using the Twilio SDK to send the OTP via SMS, and storing the OTP in the session.
  4. Implement the login form by creating a blade template and adding a ‘phone’ input field.
  5. Implement OTP verification by creating a route and controller action, checking the entered OTP against the one stored in the session, and logging the user in if the OTP is correct.

With these steps completed, you now have a Laravel app that allows users to log in using their phone number and a one-time passcode sent via SMS.

There are many potential ways you could enhance this implementation. For example, you could add the ability to resend the OTP if it expires, or add support for logging in with email as well as phone number. You could also consider implementing two-factor authentication using a tool such as Google Authenticator or Authy.

For more information on working with Laravel and Twilio, you may find the following resources helpful:

Share this:

Categorized in: