Vivek Mistry 👋

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

Book A Call
  • 25 Nov, 2025
  • 625 Views
  • A simple but powerful technique to avoid duplicate heavy queries inside the same request.

Use once() Callback in Laravel to Cache Expensive Operations

🎯 What once() Does

The callback inside once() is executed only one time per request. All other calls return the cached result, without re-running the logic.

❌ Real Problem Without once()

Imagine you access the same helper multiple times:

function getSettings()
{
    return DB::table('settings')->first();
}
$settings = getSettings();
$footerSettings = getSettings();
$headerSettings = getSettings();

This runs 3 database queries!

Heavy + unnecessary + slows down the request.

✔ Fix With once() — Only ONE Query

function getSettings()
{
    return once(function () {
        return DB::table('settings')->first();
    });
}

Now:

  • 1st call → executes the query
  • 2nd & 3rd calls → return cached result
  • Zero extra queries

This instantly:

✔ Saves queries

✔ Makes the application faster

✔ Ensures consistent data across the request

✔ Avoids unnecessary load on database


Share: