An SMS OTP looks simple —generate six digits and send them— but security lives in the details: how the code is generated, where it is stored, how long it lasts, how many attempts are allowed and how abuse is prevented. This guide shows a complete Laravel implementation you can adapt to any PHP project. Adding SMS OTP in Laravel is simpler than it looks if you follow these steps.
The rules we will implement

- A 6-digit code from a cryptographically secure generator.
- Only a hash of the code is stored, never the plain code.
- 5-minute validity and a single active code per user and purpose.
- At most 5 validation attempts.
- At most 3 requests per number every 10 minutes, to stop SMS pumping.
- Constant-time comparison and deletion of the code once used.
1. The sending service
We will use the SmsService described in our Laravel SMS guide (in Spanish), which calls the REST API with a token, an allowlisted IP and error handling.
2. The OTP service
<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\RateLimiter;
use RuntimeException;
class OtpService
{
private const TTL_SECONDS = 300; // vigencia: 5 minutos
private const MAX_ATTEMPTS = 5; // intentos de validacion
public function __construct(private SmsService $sms)
{
}
public function send(string $phone, string $purpose): void
{
// Maximo 3 solicitudes por numero cada 10 minutos (anti SMS pumping)
$limiterKey = "otp-send:{$purpose}:{$phone}";
if (RateLimiter::tooManyAttempts($limiterKey, 3)) {
throw new RuntimeException('Demasiadas solicitudes. Intente mas tarde.');
}
RateLimiter::hit($limiterKey, 600);
$code = (string) random_int(100000, 999999);
// Se guarda solo el hash; un codigo nuevo invalida el anterior
Cache::put($this->key($phone, $purpose), [
'hash' => hash_hmac('sha256', $code, config('app.key')),
'attempts' => 0,
], self::TTL_SECONDS);
$this->sms->send($phone, "MiMarca: Tu codigo es {$code}. Vence en 5 minutos. No lo compartas con nadie.");
}
public function verify(string $phone, string $purpose, string $code): bool
{
$key = $this->key($phone, $purpose);
$data = Cache::get($key);
if (! $data || $data['attempts'] >= self::MAX_ATTEMPTS) {
return false;
}
$valid = hash_equals($data['hash'], hash_hmac('sha256', $code, config('app.key')));
if ($valid) {
Cache::forget($key); // un solo uso
} else {
$data['attempts']++;
Cache::put($key, $data, self::TTL_SECONDS);
}
return $valid;
}
private function key(string $phone, string $purpose): string
{
return "otp:{$purpose}:{$phone}";
}
}
3. The endpoints
// Solicitar el codigo
public function request(Request $request, OtpService $otp)
{
$data = $request->validate(['phone' => ['required', 'regex:/^\+52\d{10}$/']]);
$otp->send($data['phone'], 'login');
return response()->json(['message' => 'Si el numero es valido, recibira un codigo.']);
}
// Validar el codigo
public function verify(Request $request, OtpService $otp)
{
$data = $request->validate([
'phone' => ['required', 'string'],
'code' => ['required', 'digits:6'],
]);
abort_unless($otp->verify($data['phone'], 'login', $data['code']), 422, 'Codigo invalido o vencido.');
// ... continuar con el inicio de sesion
}
Note that the request response does not confirm whether the number exists, so no information leaks to someone trying to enumerate users. (Code comments are in Spanish, as in our developer guides.)
Details that make the difference
- No links in the message, plus a warning not to share the code.
- Separate codes by purpose: login, recovery and transaction confirmation.
- Monitor the verification rate: validated versus sent codes. A sharp drop usually signals abuse; see how SMS OTP works.
- Plan a fallback: allow a resend after 30 to 60 seconds and offer an alternative channel if the delivery report shows it did not arrive.
- Test the full flow in sandbox before going to production.
For the security and regulatory context, see SMS OTP for authentication and verification. Need test credentials? Contact us.
Sources
- “Grupo Tecnophone API — SMS API documentation”, Grupo Tecnophone. Read source
- “NIST SP 800-63B-4: Digital Identity Guidelines — Authentication and Authenticator Management”, NIST, 2025. Read source
- “Rate Limiting”, Laravel Documentation. Read source


