PHPackages                             salehhashemi/laravel-otp-manager - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. salehhashemi/laravel-otp-manager

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

salehhashemi/laravel-otp-manager
================================

Laravel OTP manager

v1.5.3(1y ago)18713.2k—0%18[2 issues](https://github.com/salehhashemi1992/laravel-otp-manager/issues)[2 PRs](https://github.com/salehhashemi1992/laravel-otp-manager/pulls)MITPHPPHP ^8.1CI failing

Since Sep 20Pushed 11mo ago3 watchersCompare

[ Source](https://github.com/salehhashemi1992/laravel-otp-manager)[ Packagist](https://packagist.org/packages/salehhashemi/laravel-otp-manager)[ Docs](https://github.com/salehhashemi1992/laravel-otp-manager)[ RSS](/packages/salehhashemi-laravel-otp-manager/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (24)Used By (0)

Laravel OTP Manager
===================

[](#laravel-otp-manager)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1be9c804e113b22973ef77a11d3f6149e3297a8f3551e4a2ae9bc79a221f1ace/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73616c656868617368656d692f6c61726176656c2d6f74702d6d616e616765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/salehhashemi/laravel-otp-manager)[![Total Downloads](https://camo.githubusercontent.com/257149b77aff7c11adbdf5c89e9aca22ca834cbd93e212eb001af0f22660f441/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73616c656868617368656d692f6c61726176656c2d6f74702d6d616e616765722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/salehhashemi/laravel-otp-manager)[![GitHub Actions](https://camo.githubusercontent.com/bce03d260b3fc7b63b0f1c387b9a87274d083c0654e6d342c8a4f8fd87662e58/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f73616c656868617368656d69313939322f6c61726176656c2d6f74702d6d616e616765722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473)](https://github.com/salehhashemi1992/laravel-otp-manager/actions/workflows/run-tests.yml)[![GitHub Actions](https://camo.githubusercontent.com/858d280b1ae93ad049503dbcc6e40c82817c3cf23388b2ab6bba030d955efc7b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f73616c656868617368656d69313939322f6c61726176656c2d6f74702d6d616e616765722f7374617469632d616e616c797369732e796d6c3f6272616e63683d6d61696e266c6162656c3d7374617469632d616e616c79736973)](https://github.com/salehhashemi1992/laravel-otp-manager/actions/workflows/static-analysis.yml)[![codecov](https://camo.githubusercontent.com/8313896e8dd52563b538d561964c7704196bf4b777f9e6dca945d44bbb362b43/68747470733a2f2f636f6465636f762e696f2f67682f73616c656868617368656d69313939322f6c61726176656c2d6f74702d6d616e616765722f67726170682f62616467652e7376673f746f6b656e3d454a423738465432374d)](https://codecov.io/gh/salehhashemi1992/laravel-otp-manager)[![PHPStan](https://camo.githubusercontent.com/f60d96f7c2579690ab6dfa8918f777fe93a02a92301c661eb38a85861a92b780/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230382d627269676874677265656e2e7376673f7374796c653d666c6174)](https://phpstan.org/)

[![Header Image](./assets/header.png)](./assets/header.png)

The `OtpManager` class is responsible for sending and verifying one-time passwords (OTPs). It provides a comprehensive set of methods to generate, send, verify, and manage OTPs. It also integrates with Laravel cache system to throttle OTP sending and provides a layer of security by tracking OTP requests.

Features
--------

[](#features)

- **Main Features**
    - Generate OTP codes
    - Send OTPs via mobile numbers
    - Resend OTPs with built-in throttling
    - Verify OTP codes
    - Track OTP requests
- **Security**
    - Rate limiting of OTP generation attempts (`OtpRateLimiter` middleware)
    - Otp Invalidation after multiple failed verifications
    - Automatic deletion of OTP codes after successful verification
- **Configuration**
    - Customize rate-limiting thresholds, max allowed attempts, and auto-delete
- **Flexibility**
    - Supports multiple OTP types using enums
    - Customizable mobile number validation

Requirements
------------

[](#requirements)

- `PHP: ^8.1`
- `Laravel framework: ^9`

VersionL9L10L111.5✅✅✅Installation
------------

[](#installation)

To install the package, you can run the following command:

```
composer require salehhashemi/laravel-otp-manager
```

Usage
-----

[](#usage)

### Sending OTP

[](#sending-otp)

```
use Salehhashemi\OtpManager\Facade\OtpManager;

$sentOtp = OtpManager::send("1234567890");
```

### Resending OTP

[](#resending-otp)

The `sendAndRetryCheck` method will throw a `ValidationException` if you try to resend the OTP before the waiting time expires.

```
$sentOtp = OtpManager::sendAndRetryCheck("1234567890");
```

### Verifying OTP

[](#verifying-otp)

```
$isVerified = OtpManager::verify("1234567890", 123456, "uuid-string");
```

### Deleting Verification Code

[](#deleting-verification-code)

```
$isDeleted = OtpManager::deleteVerifyCode("1234567890");
```

Handling and Listening to the `OtpPrepared` Event
-------------------------------------------------

[](#handling-and-listening-to-the-otpprepared-event)

The `OtpManager` package emits an `OtpPrepared` event whenever a new OTP is generated. You can listen to this event and execute custom logic, such as sending the OTP via SMS or email.

Here's how to set up an event listener:

### Step 1: Register the Event and Listener

[](#step-1-register-the-event-and-listener)

First, you need to register the `OtpPrepared` event and its corresponding listener. Open your `EventServiceProvider` file, usually located at `app/Providers/EventServiceProvider.php`, and add the event and listener to the $listen array.

```
protected $listen = [
    \Salehhashemi\OtpManager\Events\OtpPrepared::class => [
        \App\Listeners\SendOtpNotification::class,
    ],
];
```

### Step 2: Create the Listener

[](#step-2-create-the-listener)

If the listener does not exist, you can generate it using the following Artisan command:

```
php artisan make:listener SendOtpNotification
```

### Step 3: Implement the Listener

[](#step-3-implement-the-listener)

Now open the generated `SendOtpNotification` listener file, typically located at `app/Listeners/`. You'll see a handle method, where you can add your custom logic for sending the OTP.

Here's a sample implementation:

```
use Salehhashemi\OtpManager\Events\OtpPrepared;

class SendOtpNotification
{
    public function handle(OtpPrepared $event)
    {
        $mobile = $event->mobile;
        $otpCode = $event->code;

        // Send the OTP code to the mobile number
        // You can use your preferred SMS service here.
    }
}
```

### Step 4: Test the Event Listener

[](#step-4-test-the-event-listener)

Once you've set up the listener, generate a new OTP through the `OtpManager` package to make sure the `OtpPrepared` event is being caught and the corresponding listener logic is being executed.

That's it! You've successfully set up an event listener for the `OtpPrepared` event in the `OtpManager` package.

Using Enums for OTP Types
-------------------------

[](#using-enums-for-otp-types)

You can take advantage of enums to define your OTP types. Enums provide a more expressive way to manage different categories of OTPs.

### How to Define an OTP Enum

[](#how-to-define-an-otp-enum)

```
use Salehhashemi\OtpManager\Contracts\OtpTypeInterface;

enum MyOtpEnum: string implements OtpTypeInterface
{
    case SIGNUP = 'signup';
    case RESET_PASSWORD = 'reset_password';

    public function identifier(): string
    {
        return $this->value;
    }
}
```

### Usage

[](#usage-1)

After defining your enum, you can use it just like any other OTP type:

```
OtpManager::send('1234567890', MyOtpEnum::SIGNUP);
OtpManager::verify('1234567890', $otpCode, $trackingCode, MyOtpEnum::SIGNUP);
```

Configuration
-------------

[](#configuration)

To publish the config file, run the following command:

```
php artisan vendor:publish --provider="Salehhashemi\OtpManager\OtpManagerServiceProvider" --tag="config"
```

To publish the language files, run:

```
php artisan vendor:publish --provider="Salehhashemi\OtpManager\OtpManagerServiceProvider" --tag="lang"
```

After publishing, make sure to clear the config cache to apply your changes:

```
php artisan config:clear
```

Then, you can adjust the waiting\_time, code\_min, and code\_max in the `config/otp.php`

Middleware Protection
---------------------

[](#middleware-protection)

The OtpManager package includes built-in middleware (OtpRateLimiter) to protect your application routes from excessive OTP requests. This helps prevent potential abuse.

### To apply the middleware:

[](#to-apply-the-middleware)

**Register the middleware:** Add `\Salehhashemi\OtpManager\Middleware\OtpRateLimiter::class` to the `middlewareAliases` array in your `app\Http\Kernel.php` file.

**Assign the middleware to routes:** You can apply it to specific routes or route groups where you want to implement rate limiting.

Example:

```
Route::middleware('otp-rate-limiter')->group(function () {
    // Routes that require OTP rate limiting go here
});
```

Custom Mobile Number Validation
-------------------------------

[](#custom-mobile-number-validation)

The package comes with a default mobile number validator, but you can easily use your own.

Here's how you can do it:

1. Create a Custom Validator Class First, create a class that implements `MobileValidatorInterface`. This interface expects you to define a validate method. ```
    use Salehhashemi\OtpManager\Contracts\MobileValidatorInterface;

    class CustomMobileValidator implements MobileValidatorInterface
    {
        public function validate(string $mobile): void
        {
            // Your validation logic here
        }
    }
    ```
2. Update Configuration Next, open your OTP configuration file and update the `mobile_validation_class` option to use your custom validator class: ```
    'mobile_validation_class' => CustomMobileValidator::class,
    ```

### Exceptions

[](#exceptions)

- `\InvalidArgumentException` will be thrown if the mobile number is empty.
- `\Exception` will be thrown for general exceptions, like OTP generation failures.
- `\Illuminate\Validation\ValidationException` will be thrown for throttle restrictions.
- `\Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException` will be thrown for throttled requests.

Docker Setup
------------

[](#docker-setup)

This project uses Docker for local development and testing. Make sure you have Docker and Docker Compose installed on your system before proceeding.

### Build the Docker images

[](#build-the-docker-images)

```
docker-compose build
```

### Start the services

[](#start-the-services)

```
docker-compose up -d
```

To access the PHP container, you can use:

```
docker-compose exec php bash
```

### Testing

[](#testing)

```
composer test
```

### Changelog

[](#changelog)

Please see [CHANGELOG](changelog.md) for more information what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](contributing.md) for details.

Credits
-------

[](#credits)

- [Saleh Hashemi](https://github.com/salehhashemi1992)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](license.md) for more information.

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance44

Moderate activity, may be stable

Popularity42

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 89.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~21 days

Recently: every ~46 days

Total

19

Last Release

588d ago

Major Versions

v0.9.9 → v1.0.02023-09-28

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/57674418?v=4)[salehhashemi](/maintainers/salehhashemi)[@salehhashemi](https://github.com/salehhashemi)

---

Top Contributors

[![salehhashemi1992](https://avatars.githubusercontent.com/u/81674631?v=4)](https://github.com/salehhashemi1992 "salehhashemi1992 (77 commits)")[![imahmood](https://avatars.githubusercontent.com/u/13146816?v=4)](https://github.com/imahmood "imahmood (6 commits)")[![StyleCIBot](https://avatars.githubusercontent.com/u/11048387?v=4)](https://github.com/StyleCIBot "StyleCIBot (2 commits)")[![Danger-Mkh](https://avatars.githubusercontent.com/u/54482480?v=4)](https://github.com/Danger-Mkh "Danger-Mkh (1 commits)")

---

Tags

laravellaravel-packageotpotp-generatorotp-verificationlaravelotpsecurityAuthenticationsmstwo-factor

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/salehhashemi-laravel-otp-manager/health.svg)

```
[![Health](https://phpackages.com/badges/salehhashemi-laravel-otp-manager/health.svg)](https://phpackages.com/packages/salehhashemi-laravel-otp-manager)
```

###  Alternatives

[rinvex/laravel-authy

Rinvex Authy is a simple wrapper for Authy TOTP, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest API for developers and a strong authentication platform for the enterprise.

3376.7k1](/packages/rinvex-laravel-authy)[remotemerge/totp-php

Lightweight, fast, and secure TOTP (2FA) authentication library for PHP — battle tested, dependency free, and ready for enterprise integration.

2010.2k](/packages/remotemerge-totp-php)[lakm/nopass

Provides passwordless authentication for your laravel projects.

2213.6k2](/packages/lakm-nopass)[sicaboy/laravel-mfa

A Laravel package of Multi-factor Authentication (MFA/2FA) with a middleware.

101.2k](/packages/sicaboy-laravel-mfa)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
