In this episode, we dive into Laravel's new defer()
function and explore how it helps make your apps feel more responsive by pushing longer-running tasks to the background. We start off by seeing the basics: using defer()
to log something after a request completes and understanding how it works behind the scenes with PHP processes — no queues required!
We also check out some practical examples, like deferring a database update to log user activity. You’ll see how to wire this up in middleware for just a little overhead per request, making it ideal for quick tasks you don’t want slowing down your users’ experience. There's a step-by-step on updating migrations, user models, and using the debug bar to verify the difference.
Not every background job belongs with defer()
, though. We touch on when not to use it (think: heavy work like video processing), and show you how to keep those for the job queue — including a quick look at using dispatch()
inline for small ad-hoc jobs that still need the queue’s robustness.
By the end, you'll know when to use defer()
for most performance-friendly situations, and when to fall back to the classic queue system for anything more serious.