How to generate OTP (One Time Password) in Laravel

In this post, I will show you how you can generate and validate the OTP (One Time Password) in Laravel using a simple Laravel package. https://github.com/seshac/otp-generator.

There are three major steps in this process:

  1. Generate OTP with a unique $identifier, it could be id, phone, email or any unique code attached to a user.
  2. Send to the user using any notification provider
  3. Verify using the same unique identification you chose in step 1.

Getting Started: Installation

Install the package via composer:

composer require seshac/otp-generator

Then, publish the package:

php artisan vendor:publish --provider="Seshac\Otp\OtpServiceProvider" --tag="migrations"
php artisan migrate

You can publish the config file with:

php artisan vendor:publish --provider="Seshac\Otp\OtpServiceProvider" --tag="config"

You can use the config/otp-generator.php file to configure the values based on your requirements.

Generate OTP

use Seshac\Otp\Otp;

$otp =  Otp::generate($identifier);

Verify OTP

use Seshac\Otp\Otp;

$otp = "123456"
$verify = Otp::validate($identifier, $otp);

More options to usage


use Seshac\Otp\Otp;

$otp =  Otp::setValidity(30)  // otp validity time in mins
      ->setLength(4)  // Length of the generated otp
      ->setMaximumOtpsAllowed(10) // Number of times allowed to regenerate otps
      ->setOnlyDigits(false)  // generated otp contains mixed characters ex:AB123
      ->setUseSameToken(true) // if user re-generates OTP, they will get same token
      ->generate($identifier);

$verify = Otp::setAllowedAttempts(10)->validate($identifier, $otp->token);  // number of times they can allow to attempt with wrong token

Here the GitHub repository https://github.com/seshac/otp-generator

If you find this post helpful, like share and give a follow.