The once() Helper
Memoize the result of an expensive expression so it only executes once per request, no matter how many times it is called.
Overview
The once() helper caches the return value of a callback and returns the cached result on subsequent calls within the same request lifecycle. It's memoization built right into the framework.
Usage
function getSettings(): array
{
return once(function () {
logger('Fetching settings...'); // Only logged once
return Settings::all()->pluck('value', 'key')->toArray();
});
}
getSettings(); // Executes the callback
getSettings(); // Returns cached result
getSettings(); // Returns cached result
It also works inside class methods — each unique call site is memoized independently:
class PricingService
{
public function getExchangeRates(): array
{
return once(fn () => Http::get('https://api.rates.com')->json());
}
}
When to Use
- Expensive computations called multiple times in a single request
- API calls or database queries used repeatedly across view composers, middleware, and controllers
- Avoiding redundant work without manually wiring up a cache property