PHPackages                             metasoftdevs/laravel-breeze-2fa - 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. metasoftdevs/laravel-breeze-2fa

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

metasoftdevs/laravel-breeze-2fa
===============================

Advanced two-factor authentication package for Laravel Breeze with multi-channel support (TOTP, Email, SMS) and custom authentication integration

210PHPCI failing

Since Aug 31Pushed 8mo agoCompare

[ Source](https://github.com/CodeWith-PeterBull/laravel-breeze-2fa)[ Packagist](https://packagist.org/packages/metasoftdevs/laravel-breeze-2fa)[ RSS](/packages/metasoftdevs-laravel-breeze-2fa/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Breeze 2FA Package
==========================

[](#laravel-breeze-2fa-package)

[![Latest Version on Packagist](https://camo.githubusercontent.com/a5de77be1f7f4911e4c16c424ee57b0e0cad7b8c42d07abd4f71a4c5b9ce045f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d657461736f6674646576732f6c61726176656c2d627265657a652d3266612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/metasoftdevs/laravel-breeze-2fa)[![GitHub Tests Action Status](https://camo.githubusercontent.com/7b5cc1ce567d48ef68d738dcdb36b992ec905db43b79e62225d5c73eae2ce0e2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f6d657461736f6674646576732f6c61726176656c2d627265657a652d3266612f72756e2d74657374733f6c6162656c3d7465737473)](https://github.com/metasoftdevs/laravel-breeze-2fa/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/44d797813efcaa4a2af08afc3328e73d7bae7f236236f4fb8320af2c6ecc896e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f6d657461736f6674646576732f6c61726176656c2d627265657a652d3266612f466978253230504850253230636f64652532307374796c652532306973737565733f6c6162656c3d636f64652532307374796c65)](https://github.com/metasoftdevs/laravel-breeze-2fa/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/b26e381b4d17387cc92e5da8bd3c4f17d8d5840c884ca39d8fb951a8abeeb153/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d657461736f6674646576732f6c61726176656c2d627265657a652d3266612e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/metasoftdevs/laravel-breeze-2fa)

An advanced, highly customizable two-factor authentication (2FA) package for Laravel Breeze that supports multiple authentication methods and seamlessly integrates with both Breeze and custom authentication systems.

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

[](#-features)

- **🔐 Multiple 2FA Methods**: TOTP (Authenticator Apps), Email OTP, SMS OTP
- **🔑 Recovery Codes**: Secure backup codes for account recovery
- **📱 Device Remembering**: Optional "trust this device" functionality
- **🛡️ Security First**: Rate limiting, encryption, CSRF protection
- **🎨 Laravel Breeze Integration**: Drop-in compatibility with Breeze
- **🔧 Highly Customizable**: Extensive configuration options
- **📋 Custom Auth Support**: Works with any Laravel authentication guard
- **🧪 Fully Tested**: Comprehensive test suite with 90%+ coverage
- **📚 Well Documented**: Extensive documentation and examples

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

[](#-requirements)

- PHP 8.1 or higher
- Laravel 10.0 or higher
- Laravel Breeze (for seamless integration)

🚀 Quick Start
-------------

[](#-quick-start)

### Installation

[](#installation)

Install the package via Composer:

```
composer require metasoftdevs/laravel-breeze-2fa
```

### Basic Setup

[](#basic-setup)

1. **Publish and run migrations:**

```
php artisan vendor:publish --provider="MetaSoftDevs\LaravelBreeze2FA\TwoFactorServiceProvider" --tag="two-factor-migrations"
php artisan migrate
```

2. **Publish configuration (optional):**

```
php artisan vendor:publish --provider="MetaSoftDevs\LaravelBreeze2FA\TwoFactorServiceProvider" --tag="two-factor-config"
```

3. **Install the package setup:**

```
php artisan two-factor:install
```

### Laravel Breeze Integration

[](#laravel-breeze-integration)

If you're using Laravel Breeze, the package will automatically integrate with your existing authentication flow:

```
// In your login controller or middleware
use MetaSoftDevs\LaravelBreeze2FA\Facades\TwoFactor;

// After successful password authentication
if (TwoFactor::isEnabledForUser($user)) {
    if (!TwoFactor::isDeviceRemembered($user)) {
        // Redirect to 2FA challenge
        return redirect()->route('two-factor.challenge');
    }
}
```

📖 Usage Examples
----------------

[](#-usage-examples)

### Enabling 2FA for a User

[](#enabling-2fa-for-a-user)

```
use MetaSoftDevs\LaravelBreeze2FA\Facades\TwoFactor;

// Enable TOTP (Authenticator App)
$setup = TwoFactor::enable($user, 'totp');
$qrCodeUrl = $setup['qr_code_url'];
$secret = $setup['secret'];
$recoveryCodes = $setup['recovery_codes'];

// Enable Email OTP
$setup = TwoFactor::enable($user, 'email');
// A verification email will be sent automatically

// Enable SMS OTP
$setup = TwoFactor::enable($user, 'sms');
// A verification SMS will be sent automatically
```

### Confirming 2FA Setup

[](#confirming-2fa-setup)

```
// User enters the code from their authenticator app/email/SMS
$isConfirmed = TwoFactor::confirm($user, $userProvidedCode);

if ($isConfirmed) {
    // 2FA is now active for the user
    return redirect()->route('dashboard')->with('success', '2FA enabled successfully!');
}
```

### Verifying 2FA During Login

[](#verifying-2fa-during-login)

```
// In your authentication flow
try {
    $verified = TwoFactor::verify($user, $code, $rememberDevice = true);

    if ($verified) {
        // User is authenticated, proceed with login
        Auth::login($user);
        return redirect()->intended('dashboard');
    }
} catch (\MetaSoftDevs\LaravelBreeze2FA\Exceptions\InvalidCodeException $e) {
    return back()->withErrors(['code' => 'Invalid verification code']);
} catch (\MetaSoftDevs\LaravelBreeze2FA\Exceptions\RateLimitExceededException $e) {
    return back()->withErrors(['code' => 'Too many attempts. Please try again later.']);
}
```

### Disabling 2FA

[](#disabling-2fa)

```
$disabled = TwoFactor::disable($user);

if ($disabled) {
    return redirect()->back()->with('success', '2FA has been disabled.');
}
```

### Getting User's 2FA Status

[](#getting-users-2fa-status)

```
$status = TwoFactor::getStatus($user);

/*
Returns:
[
    'enabled' => true,
    'method' => 'totp',
    'confirmed' => true,
    'recovery_codes_count' => 6,
    'can_generate_recovery_codes' => true
]
*/
```

🔧 Configuration
---------------

[](#-configuration)

The package offers extensive configuration options. Publish the config file to customize:

```
php artisan vendor:publish --provider="MetaSoftDevs\LaravelBreeze2FA\TwoFactorServiceProvider" --tag="two-factor-config"
```

### Key Configuration Options

[](#key-configuration-options)

```
// config/two-factor.php

return [
    // Enable/disable the entire 2FA system
    'enabled' => env('TWO_FACTOR_ENABLED', true),

    // Require all users to set up 2FA
    'required' => env('TWO_FACTOR_REQUIRED', false),

    // Configure available methods
    'methods' => [
        'totp' => [
            'enabled' => true,
            'issuer' => env('APP_NAME'),
            'window' => 1, // Time drift tolerance
        ],
        'email' => [
            'enabled' => true,
            'expiry' => 300, // 5 minutes
        ],
        'sms' => [
            'enabled' => false,
            'provider' => 'twilio',
        ],
    ],

    // Recovery codes settings
    'recovery_codes' => [
        'enabled' => true,
        'count' => 8,
        'length' => 10,
    ],

    // Device remembering
    'remember_device' => [
        'enabled' => true,
        'duration' => 30 * 24 * 60, // 30 days
    ],

    // Rate limiting
    'rate_limiting' => [
        'max_attempts' => 5,
        'decay_minutes' => 15,
    ],
];
```

🔒 SMS Configuration
-------------------

[](#-sms-configuration)

For SMS OTP, configure your provider credentials:

### Twilio

[](#twilio)

```
TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=your_twilio_number
```

### Vonage (Nexmo)

[](#vonage-nexmo)

```
VONAGE_API_KEY=your_api_key
VONAGE_API_SECRET=your_api_secret
VONAGE_PHONE_NUMBER=your_sender_id
```

🎨 Frontend Integration
----------------------

[](#-frontend-integration)

### Blade Templates

[](#blade-templates)

The package includes pre-built Blade templates that you can customize:

```
php artisan vendor:publish --provider="MetaSoftDevs\LaravelBreeze2FA\TwoFactorServiceProvider" --tag="two-factor-views"
```

### Vue.js/Inertia.js

[](#vuejsinertiajs)

For Vue.js applications using Inertia:

```
// Setup 2FA
const setup2FA = async (method) => {
  const response = await axios.post("/two-factor/enable", { method });

  if (method === "totp") {
    // Show QR code: response.data.qr_code_url
    showQRCode(response.data.qr_code_url);
  }

  // Show recovery codes
  showRecoveryCodes(response.data.recovery_codes);
};

// Verify setup
const confirm2FA = async (code) => {
  await axios.post("/two-factor/confirm", { code });
  // 2FA is now enabled
};
```

### Livewire

[](#livewire)

For Livewire components:

```
class TwoFactorSetup extends Component
{
    public $method = 'totp';
    public $code = '';
    public $qrCodeUrl = '';
    public $recoveryCodes = [];

    public function enable()
    {
        $setup = TwoFactor::enable(auth()->user(), $this->method);
        $this->qrCodeUrl = $setup['qr_code_url'] ?? '';
        $this->recoveryCodes = $setup['recovery_codes'] ?? [];
    }

    public function confirm()
    {
        TwoFactor::confirm(auth()->user(), $this->code);
        session()->flash('message', '2FA enabled successfully!');
    }
}
```

🛠️ Custom Authentication Integration
------------------------------------

[](#️-custom-authentication-integration)

For custom authentication systems, implement the 2FA flow manually:

```
use MetaSoftDevs\LaravelBreeze2FA\Facades\TwoFactor;

// In your custom login controller
class CustomLoginController extends Controller
{
    public function authenticate(Request $request)
    {
        // Your existing authentication logic
        $user = $this->attemptLogin($request);

        if ($user && TwoFactor::isEnabledForUser($user)) {
            if (!TwoFactor::isDeviceRemembered($user)) {
                // Store user in session for 2FA challenge
                session(['2fa_user_id' => $user->id]);
                return redirect()->route('two-factor.challenge');
            }
        }

        // Complete login
        Auth::login($user);
        return redirect()->intended();
    }

    public function challenge()
    {
        // Show 2FA challenge form
        return view('auth.two-factor-challenge');
    }

    public function verify(Request $request)
    {
        $userId = session('2fa_user_id');
        $user = User::find($userId);

        $verified = TwoFactor::verify($user, $request->code, $request->boolean('remember'));

        if ($verified) {
            session()->forget('2fa_user_id');
            Auth::login($user);
            return redirect()->intended();
        }

        return back()->withErrors(['code' => 'Invalid code']);
    }
}
```

🧪 Testing
---------

[](#-testing)

Run the package tests:

```
composer test
```

Run tests with coverage:

```
composer test-coverage
```

📋 Commands
----------

[](#-commands)

The package includes several Artisan commands:

```
# Install the package (publish assets, run migrations)
php artisan two-factor:install

# Generate recovery codes for a user
php artisan two-factor:recovery-codes {user-id}

# Clean up expired sessions and codes
php artisan two-factor:cleanup

# Show 2FA statistics
php artisan two-factor:stats
```

🔐 Security Considerations
-------------------------

[](#-security-considerations)

- **Secrets Encryption**: TOTP secrets are encrypted in the database
- **Rate Limiting**: Prevents brute force attacks on 2FA codes
- **Recovery Codes**: Securely hashed and single-use
- **Device Tokens**: Cryptographically secure device remembering
- **Audit Trail**: All authentication attempts are logged
- **CSRF Protection**: All forms include CSRF tokens

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

[](#-contributing)

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

### Development Setup

[](#development-setup)

1. Clone the repository
2. Install dependencies: `composer install`
3. Run tests: `composer test`
4. Check code style: `composer format`

📜 Changelog
-----------

[](#-changelog)

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

🛡️ Security
-----------

[](#️-security)

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

📄 License
---------

[](#-license)

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

🙏 Credits
---------

[](#-credits)

- [Meta Software Developers](https://github.com/metasoftdevs)
- [All Contributors](../../contributors)

🔗 Related Packages
------------------

[](#-related-packages)

- [Laravel Breeze](https://github.com/laravel/breeze) - Simple authentication scaffolding
- [Laravel Fortify](https://github.com/laravel/fortify) - Backend authentication services
- [pragmarx/google2fa](https://github.com/antonioribeiro/google2fa) - Google2FA for Laravel

---

 **Built with ❤️ by [Meta Software Developers](https://metasoftdevs.com)**

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance43

Moderate activity, may be stable

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity13

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/47f2680c64f26bc13d994ab2e960dcaecbe2fe4e6f35be5eeec5af2d0814d846?d=identicon)[metasoftdevs](/maintainers/metasoftdevs)

---

Top Contributors

[![CodeWith-PeterBull](https://avatars.githubusercontent.com/u/77413110?v=4)](https://github.com/CodeWith-PeterBull "CodeWith-PeterBull (9 commits)")

### Embed Badge

![Health badge](/badges/metasoftdevs-laravel-breeze-2fa/health.svg)

```
[![Health](https://phpackages.com/badges/metasoftdevs-laravel-breeze-2fa/health.svg)](https://phpackages.com/packages/metasoftdevs-laravel-breeze-2fa)
```

###  Alternatives

[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[league/oauth1-client

OAuth 1.0 Client Library

99698.8M106](/packages/league-oauth1-client)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[gesdinet/jwt-refresh-token-bundle

Implements a refresh token system over Json Web Tokens in Symfony

70516.4M35](/packages/gesdinet-jwt-refresh-token-bundle)[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

41721.2M118](/packages/league-oauth2-google)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)

PHPackages © 2026

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