php 50 lines · 7 steps

Phone verification codes in Laravel

A service that rate-limits, hashes, and expires SMS verification codes using Laravel's Cache and RateLimiter facades.

Explained by highlit
1<?php
2 
3namespace App\Services;
4 
5use App\Models\User;
6use App\Notifications\VerificationCodeNotification;
7use Illuminate\Support\Facades\Cache;
8use Illuminate\Support\Facades\RateLimiter;
9 
10class PhoneVerificationService
11{
12 private const TTL = 300;
13 
14 public function send(User $user): void
15 {
16 $key = 'phone-verify:send:' . $user->id;
17 
18 if (RateLimiter::tooManyAttempts($key, 3)) {
19 abort(429, 'Too many code requests. Please wait a moment.');
20 }
21 
22 RateLimiter::hit($key, 60);
23 
24 $code = (string) random_int(100000, 999999);
25 
26 Cache::put($this->cacheKey($user), hash('sha256', $code), self::TTL);
27 
28 $user->notify(new VerificationCodeNotification($code));
29 }
30 
31 public function confirm(User $user, string $code): bool
32 {
33 $stored = Cache::get($this->cacheKey($user));
34 
35 if ($stored === null || ! hash_equals($stored, hash('sha256', $code))) {
36 return false;
37 }
38 
39 Cache::forget($this->cacheKey($user));
40 
41 $user->forceFill(['phone_verified_at' => now()])->save();
42 
43 return true;
44 }
45 
46 private function cacheKey(User $user): string
47 {
48 return "phone-verify:code:{$user->id}";
49 }
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Rate limiting per user stops abuse of code-sending endpoints before any work happens.
  2. 2Storing a hash of the code instead of the plaintext limits the blast radius if the cache is compromised.
  3. 3A short cache TTL gives one-time codes automatic expiry with no manual cleanup.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Phone verification codes in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code