php
43 lines · 7 steps
Debouncing Eloquent jobs in Laravel
A Project model that reschedules metric recalculation only when relevant fields change, using a cache token to debounce stale jobs.
Explained by
highlit
1<?php
2
3namespace App\Models;
4
5use App\Jobs\RecalculateProjectMetrics;
6use Illuminate\Database\Eloquent\Model;
7use Illuminate\Support\Facades\Cache;
8
9class Project extends Model
10{
11 protected $fillable = ['name', 'budget', 'status'];
12
13 protected static function booted(): void
14 {
15 static::saved(function (Project $project) {
16 if (! $project->wasChanged(['budget', 'status'])) {
17 return;
18 }
19
20 $project->scheduleMetricsRecalculation();
21 });
22 }
23
24 public function scheduleMetricsRecalculation(int $delaySeconds = 30): void
25 {
26 $token = (string) now()->valueOf();
27
28 Cache::put($this->debounceCacheKey(), $token, now()->addSeconds($delaySeconds + 10));
29
30 RecalculateProjectMetrics::dispatch($this->id, $token)
31 ->delay(now()->addSeconds($delaySeconds));
32 }
33
34 public function debounceIsStale(string $token): bool
35 {
36 return Cache::get($this->debounceCacheKey()) !== $token;
37 }
38
39 protected function debounceCacheKey(): string
40 {
41 return "project:{$this->id}:metrics-debounce";
42 }
43}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Model events can trigger side effects only when the fields you care about actually change.
- 2A cache-stored token lets a delayed job detect whether it was superseded by a newer trigger.
- 3Debouncing bursts of writes into a single delayed job avoids redundant expensive work.
Related explainers
php
function fuzzySearch(string $query, array $items, int $limit = 10): array { $query = mb_strtolower(trim($query));
Building a ranked fuzzy search in PHP
fuzzy-search
string-matching
ranking
Intermediate
7 steps
typescript
type CurrencyFormatOptions = { locale?: string; currency: string; showDecimals?: boolean;
Caching Intl.NumberFormat for currency
memoization
internationalization
caching
Intermediate
9 steps
php
<?php namespace App\Http\Controllers\Api;
Cursor pagination in a Laravel API
pagination
cursor
keyset
Intermediate
9 steps
php
<?php namespace App\Queue;
A stable priority job queue in PHP
priority-queue
data-structures
closures
Intermediate
8 steps
php
<?php namespace App\Support;
Normalizing phone numbers to E.164 in PHP
input-validation
normalization
regular-expressions
Intermediate
8 steps
php
final class Route { private string $regex; private array $paramNames = [];
Compiling route patterns into regex in PHP
routing
regex
parsing
Intermediate
8 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/debouncing-eloquent-jobs-in-laravel-explained-php-7ba2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.