DEV Community


Easy way to Generate and Validate OTP in the Laravel

sesha profile image Sesha 惻2 min read

In this post I will show how to generate and validate the OTP (One Time Password) using a simple Laravel package.

So, Let's start and follow below three simple steps.

  1. You can generate OTP using any unique identification (Prefer Mobile number or Email),
  2. Send to end user using any notification provider
  3. Finally, verify using the same unique identification.

Installation and Setup process :


You can install the package via composer:

composer require seshac/otp-generator
Enter fullscreen mode Exit fullscreen mode

You can publish and run the migrations with:

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

You can publish the config file with:

php artisan vendor:publish --provider="Seshac\Otp\OtpServiceProvider" --tag="config"
Enter fullscreen mode Exit fullscreen mode

Once you published you can configure all otp-generator.php config values based on your requirements.


use Seshac\Otp\Otp;
$otp =  Otp::generate($identifier);
$verify = Otp::validate($identifier, $otp->token);
// response
  "status": true
  "message": "OTP is valid"
Enter fullscreen mode Exit fullscreen mode

You have control to update the setting at otp-generator.php config file, but you control while generating also

Advance Usage

use Seshac\Otp\Otp;
$otp =  Otp::setValidity(30)  // otp validity time in mins
      ->setLength(4)  // Lenght of the generated otp
      ->setMaximumOtpsAllowed(10) // Number of times allowed to regenerate otps
      ->setOnlyDigits(false)  // generated otp contains mixed characters ex:ad2312
      ->setUseSameToken(true) // if you re-generate OTP, you will get same token
$verify = Otp::setAllowedAttempts(10) // number of times they can allow to attempt with wrong token
    ->validate($identifier, $otp->token);

Enter fullscreen mode Exit fullscreen mode

Here the GitHub repository

If you find any issues, please, feel to free open an issue here.

Discussion (2)

Editor guide
mdhesari profile image
rubab2020 profile image

migration file is not generated