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
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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.