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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Rate limiting per user stops abuse of code-sending endpoints before any work happens.
- 2Storing a hash of the code instead of the plaintext limits the blast radius if the cache is compromised.
- 3A short cache TTL gives one-time codes automatic expiry with no manual cleanup.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
php
<?php namespace App\Services;
Batch image resizing with PHP GD
image-processing
constructor-promotion
match-expression
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/phone-verification-codes-in-laravel-explained-php-3f1d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.