Vivek Mistry 👋

I’m a Certified Senior Laravel Developer with 8+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 05 Jan, 2026
  • 301 Views
  • A smart way to delay expensive logic in Laravel without breaking your application flow.

Speed Up Laravel Requests with defer(): Run Code Only When It’s Actually Needed

In many Laravel applications, we execute logic too early — even when the result might never be used. This is common with heavy calculations, service resolution, or conditional queries.

Laravel gives us a clean solution for this problem: the defer() helper.

When used correctly, defer() can improve performance, reduce unnecessary work, and keep your code expressive.

❌ The Common Mistake

Consider this example:

$totalSales = Order::where('status', 'completed')->sum('amount');

if ($request->has('show_sales')) {
    return $totalSales;
}

Even if show_sales is not requested, the database query still runs.

✅ The Better Approach Using defer()

$totalSales = defer(function () {
    return Order::where('status', 'completed')->sum('amount');
});

if ($request->has('show_sales')) {
    return $totalSales();
}

Now the query executes only if the value is actually needed.

🧠 What defer() Does

  • Delays execution of the callback
  • Runs logic only when accessed
  • Keeps code readable and intentional
  • Avoids premature computation

Think of it as lazy execution for values, not collections.

🧪 Real-World Use Cases

Conditional Dashboard Metrics

$stats = defer(fn () => DashboardService::loadStats());

return [
    'user' => auth()->user(),
    'stats' => $request->boolean('stats') ? $stats() : null,
];

Optional API Fields

$profile = defer(fn () => UserProfile::find($id));

return response()->json([
    'id' => $id,
    'profile' => $request->has('profile') ? $profile() : null,
]);

Share: