Installation:
composer require laragear/two-factor
php artisan two-factor:install
php artisan migrate
Configure User Model:
Add the contract and trait to your User model:
use Laragear\TwoFactor\TwoFactorAuthentication;
use Laragear\TwoFactor\Contracts\TwoFactorAuthenticatable;
class User extends Authenticatable implements TwoFactorAuthenticatable
{
use TwoFactorAuthentication;
}
First Use Case:
Integrate the Auth2FA facade into your login logic:
use Laragear\TwoFactor\Facades\Auth2FA;
public function login(Request $request)
{
$attempt = Auth2FA::attempt($request->only('email', 'password'));
return $attempt ? redirect()->home() : back()->withErrors(['email' => 'Invalid credentials']);
}
Enabling 2FA:
$secret = auth()->user()->createTwoFactorAuth();
return view('2fa.setup', ['qr_code' => $secret->toQr()]);
$confirmed = auth()->user()->confirmTwoFactorAuth($request->code);
Login Flow:
Auth2FA::attempt() to handle credentials and 2FA validation in one call.Auth2FA::message('2FA required')
->input('two_factor_code')
->attempt($credentials);
Recovery Codes:
return auth()->user()->getRecoveryCodes();
auth()->user()->generateRecoveryCodes();
2fa.enabled to enforce 2FA:
Route::get('/dashboard', function () {})->middleware('2fa.enabled');
TwoFactorEnabled) to trigger notifications or logs.php artisan vendor:publish --provider="Laragear\TwoFactor\TwoFactorServiceProvider"
Session Handling:
file, database, or redis).session()->forget('_2fa_login');
Recovery Codes:
generateRecoveryCodesUsing() if needed.Time Synchronization:
Failed 2FA Codes:
toUri() output).Middleware Bypass:
2fa.enabled, 2fa.confirm) only applies to models implementing TwoFactorAuthenticatable. Exclude non-2FA users explicitly:
if (!auth()->user() instanceof TwoFactorAuthenticatable) {
return redirect()->route('home');
}
Custom Validation:
TwoFactorAuthentication trait to add logic (e.g., rate-limiting 2FA attempts):
public function confirmTwoFactorAuth($code)
{
if ($this->failedAttempts() >= 5) {
throw new \Exception('Too many attempts');
}
return parent::confirmTwoFactorAuth($code);
}
Safe Devices:
TwoFactorAuthentication trait:
protected function isSafeDevice(): bool
{
return request()->cookie('trusted_device') === 'true';
}
QR Code Customization:
php artisan vendor:publish --tag=two-factor-views
How can I help you explore Laravel packages today?