PHPackages                             turahe/otp - 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. turahe/otp

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

turahe/otp
==========

A robust Laravel package for generating and validating One-Time Passwords (OTP) with email integration, automatic cleanup, and comprehensive testing support for PHP 8.2+

v1.1.1(6mo ago)0265[7 PRs](https://github.com/turahe/laravel-otp/pulls)MITPHPPHP ^8.2CI passing

Since Oct 8Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/turahe/laravel-otp)[ Packagist](https://packagist.org/packages/turahe/otp)[ RSS](/packages/turahe-otp/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (4)Dependencies (10)Versions (14)Used By (0)

Laravel OTP ▲
=============

[](#laravel-otp-)

[![Tests](https://github.com/turahe/laravel-otp/workflows/CI/badge.svg)](https://github.com/turahe/laravel-otp/actions)[![Code Quality](https://github.com/turahe/laravel-otp/workflows/CI/badge.svg)](https://github.com/turahe/laravel-otp/actions)[![codecov](https://camo.githubusercontent.com/bd47c84996010435de029cada7e3bb45233c52aeea6f981f584c4beccfb23528/68747470733a2f2f636f6465636f762e696f2f67682f7475726168652f6c61726176656c2d6f74702f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/turahe/laravel-otp)[![Latest Stable Version](https://camo.githubusercontent.com/2cc807987047457cb2f5fae637451f37f3b426fa3427f9bc50e0c613f7c15521/68747470733a2f2f706f7365722e707567782e6f72672f7475726168652f6f74702f762f737461626c65)](https://packagist.org/packages/turahe/otp)[![Total Downloads](https://camo.githubusercontent.com/3f5a96ec199c241650e446e23c17ee77930e448a26a3b6bcf8b05a5650039eb6/68747470733a2f2f706f7365722e707567782e6f72672f7475726168652f6f74702f646f776e6c6f616473)](https://packagist.org/packages/turahe/otp)[![License](https://camo.githubusercontent.com/933392ca6bd58fd587830092ae70c8234ad599971208110346a46552d32c9ef5/68747470733a2f2f706f7365722e707567782e6f72672f7475726168652f6f74702f6c6963656e7365)](https://packagist.org/packages/turahe/otp)[![PHP Version](https://camo.githubusercontent.com/e6b72edd7890b1bba8f080796540f9d2a88ea9adcbd7566a5c5b873b093a8fc6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f7475726168652f6f7470)](https://packagist.org/packages/turahe/otp)[![Laravel Version](https://camo.githubusercontent.com/0fdd2ad6f71e1bec424f883f9bbe83c0ae9e2b7961e53058be0c2c57fde63dc4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d3130253230253743253230313125323025374325323031322d4646324432303f6c6f676f3d6c61726176656c)](https://laravel.com)[![PHPStan](https://camo.githubusercontent.com/6d4bb6ed0743c01667c1e3a0e9691481682b73f9a981190a9bd9b72ca7cfa443/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d4c6576656c253230382532302545322539432539332d627269676874677265656e2e737667)](https://github.com/phpstan/phpstan)

Introduction 🖖
--------------

[](#introduction-)

A robust Laravel package for generating and validating OTPs (One Time Passwords) with comprehensive test coverage and modern CI/CD pipeline. Perfect for authentication systems, email verification, and secure access control.

Features ✨
----------

[](#features-)

- 🔐 **Secure OTP Generation**: 6-digit numeric tokens with configurable expiry
- 📧 **Email Integration**: Built-in email sending with customizable templates
- 🧪 **Comprehensive Testing**: 126+ tests with 100% coverage of core functionality
- 🚀 **Modern CI/CD**: GitHub Actions with PHP 8.2-8.4 and Laravel 10-12 support
- 📱 **Flexible Identity**: Support for email, phone numbers, or any string identifier
- ⏰ **Automatic Cleanup**: Scheduled cleanup of expired tokens
- 🎨 **PSR-12 Compliant**: Clean, maintainable code following Laravel best practices

Requirements 📋
--------------

[](#requirements-)

- **PHP**: ^8.2
- **Laravel**: ^10.0 || ^11.0 || ^12.0
- **Database**: MySQL, PostgreSQL, SQLite, or SQL Server

Installation 💽
--------------

[](#installation-)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require turahe/otp
```

### 2. Add Service Provider

[](#2-add-service-provider)

Add to `config/app.php` providers array:

```
'providers' => [
    // ...
    Turahe\Otp\OtpServiceProvider::class,
],
```

### 3. Add Facade Alias (Optional)

[](#3-add-facade-alias-optional)

Add to `config/app.php` aliases array:

```
'aliases' => [
    // ...
    'Otp' => Turahe\Otp\Facades\Otp::class,
],
```

### 4. Publish Configuration (Optional)

[](#4-publish-configuration-optional)

```
php artisan vendor:publish --provider="Turahe\Otp\OtpServiceProvider"
```

### 5. Run Migrations

[](#5-run-migrations)

```
php artisan migrate
```

Configuration ⚙️
----------------

[](#configuration-️)

The package configuration file (`config/otp.php`) allows you to customize:

```
return [
    // Token expiry time in minutes
    'expires' => 15,

    // Database table name
    'table' => 'otp_tokens',

    // Password generator type (string, numeric, numeric-no-0)
    'password_generator' => 'numeric',

    // Default notification channels
    'default_channels' => 'mail',
];
```

Usage 🧨
-------

[](#usage-)

### Basic OTP Generation

[](#basic-otp-generation)

```
use Turahe\Otp\Facades\Otp;

// Generate OTP for email (default 15 minutes expiry)
$otp = Otp::generate('user@example.com');

// Generate OTP with custom expiry (10 minutes)
$otp = Otp::generate('user@example.com', 10);

// Generate OTP for phone number
$otp = Otp::generate('+1234567890', 5);
```

### OTP Validation

[](#otp-validation)

```
// Validate OTP
$isValid = Otp::validate('user@example.com', '123456');

if ($isValid) {
    // OTP is valid and has been consumed
    echo "OTP verified successfully!";
} else {
    // OTP is invalid or expired
    echo "Invalid or expired OTP";
}
```

### Email Integration

[](#email-integration)

```
use Turahe\Otp\Jobs\SendOtp;

// Send OTP via email
$otp = Otp::generate('user@example.com');
dispatch(new SendOtp('user@example.com', $otp));
```

### Custom Email Templates

[](#custom-email-templates)

The package includes a default email template at `resources/views/emails/otp.blade.php`. You can customize it by publishing the views:

```
php artisan vendor:publish --tag=otp-views
```

### Cleanup Expired Tokens

[](#cleanup-expired-tokens)

```
# Manual cleanup
php artisan otp:clean

# Scheduled cleanup (add to app/Console/Kernel.php)
protected function schedule(Schedule $schedule)
{
    $schedule->command('otp:clean')->daily();
}
```

Testing 🧪
---------

[](#testing-)

The package includes comprehensive test coverage organized into Unit and Feature tests:

```
# Run all tests
composer test

# Run only unit tests (isolated class testing)
composer test:unit

# Run only feature tests (integration testing)
composer test:feature

# Run with coverage report
composer test -- --coverage-html coverage/
```

### Test Structure

[](#test-structure)

**Unit Tests** (`tests/Unit/`) - Isolated class testing

- **Helper Functions**: Phone validation, email provider extraction, disposable email detection
- **Token Service**: OTP generation, validation, expiry handling, serialization

**Feature Tests** (`tests/Feature/`) - Integration testing

- **SendOtp Job**: Email queuing, parameter handling, edge cases
- **RemoveInvalidateOtp Command**: Expired token cleanup, batch processing

### Test Coverage Summary

[](#test-coverage-summary)

- **Total Tests**: 126
- **Total Assertions**: 274
- **Code Coverage**: Core functionality fully covered
- **PHP Versions**: 8.2, 8.3, 8.4
- **Laravel Versions**: 10.x, 11.x, 12.x

CI/CD Pipeline 🚀
----------------

[](#cicd-pipeline-)

### Continuous Integration

[](#continuous-integration)

The GitHub Actions workflow runs on every push and pull request:

- **Matrix Testing**: PHP 8.2, 8.3, 8.4 × Laravel 10, 11, 12
- **Code Quality**: PHP CS Fixer (PSR-12) and PHPStan Level 8 static analysis (zero errors)
- **Security**: Composer security audit
- **Validation**: Composer.json validation and lock file checks

### Release Management

[](#release-management)

Automated releases are created when semantic version tags are pushed:

```
git tag v1.2.0
git push origin v1.2.0
```

### Local Development

[](#local-development)

Run the same checks locally:

```
# Code quality checks
composer cs-check
composer stan

# Fix code style
composer cs-fix

# Security audit
composer audit

# Full test suite
composer test
```

API Reference 📚
---------------

[](#api-reference-)

### Otp Facade

[](#otp-facade)

MethodParametersReturnsDescription`generate()``string $identity, int $expiresAt = 15``OtpToken`Generate new OTP`validate()``string $identity, string $token``bool`Validate OTP### Token Service

[](#token-service)

MethodParametersReturnsDescription`identity()`-`mixed`Get token identity`token()`-`string`Get token value`plainText()`-`string`Get plain text token value`expired()`-`bool`Check if token expired`timeLeft()`-`int`Get seconds until expiry### Helper Functions

[](#helper-functions)

FunctionParametersReturnsDescription`validation_number()``string $number, string $country = 'ID'``bool`Validate phone number`format_number()``string $number, string $country = 'ID'``string`Format phone number`get_email_provider()``string $email``string`Extract email provider`validate_email()``string $email``bool`Check if email is disposableExamples 📝
----------

[](#examples-)

### Authentication Flow

[](#authentication-flow)

```
// 1. Generate OTP for login
$otp = Otp::generate($user->email, 10);

// 2. Send OTP via email
dispatch(new SendOtp($user->email, $otp));

// 3. User enters OTP
$userOtp = request('otp');

// 4. Validate OTP
if (Otp::validate($user->email, $userOtp)) {
    // Login successful
    Auth::login($user);
    return redirect()->intended('/dashboard');
} else {
    // Invalid OTP
    return back()->withErrors(['otp' => 'Invalid or expired OTP']);
}
```

### Phone Number Validation

[](#phone-number-validation)

```
use Turahe\Otp\Helpers;

// Validate Indonesian phone number
$phone = '+6281234567890';
if (validation_number($phone, 'ID')) {
    $formatted = format_number($phone, 'ID');
    // +62 812-3456-7890
}
```

### Email Provider Detection

[](#email-provider-detection)

```
use Turahe\Otp\Helpers;

$email = 'user@gmail.com';
$provider = get_email_provider($email);
// Returns: 'gmail'

// Check if disposable email
if (validate_email($email)) {
    // Email is not disposable
} else {
    // Email is disposable
}
```

Contributing 🤝
--------------

[](#contributing-)

We welcome contributions! Please see our contributing guidelines:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass (`composer test`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

### Development Setup

[](#development-setup)

```
# Clone repository
git clone https://github.com/turahe/laravel-otp.git
cd laravel-otp

# Install dependencies
composer install

# Run tests
composer test

# Check code quality
composer cs-check
composer stan
```

Security 🔒
----------

[](#security-)

If you discover any security-related issues, please email  instead of using the issue tracker.

License 📄
---------

[](#license-)

This package is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

Support 💬
---------

[](#support-)

- **Documentation**: [GitHub Wiki](https://github.com/turahe/laravel-otp/wiki)
- **Issues**: [GitHub Issues](https://github.com/turahe/laravel-otp/issues)
- **Discussions**: [GitHub Discussions](https://github.com/turahe/laravel-otp/discussions)

Changelog 📋
-----------

[](#changelog-)

See [CHANGELOG.md](CHANGELOG.md) for a detailed history of changes.

---

**Made with ❤️ by [Turahe](https://github.com/turahe)**

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance75

Regular maintenance activity

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~13 days

Total

4

Last Release

180d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f3513bd6100438bcb8c6b1a7e241a66e1ddaf1c11ee33883e06ef4a2784120db?d=identicon)[turahe](/maintainers/turahe)

---

Top Contributors

[![turahe](https://avatars.githubusercontent.com/u/6832622?v=4)](https://github.com/turahe "turahe (16 commits)")

---

Tags

laravelotpsecurityAuthenticationtoken2faverificationone-time-passwordemail-verification

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/turahe-otp/health.svg)

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

###  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)[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)
