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
<?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
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
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 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/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.