Mircha Emanuel D'Angelo

Easy Memoization with Laravel 11

Mircha Emanuel D'Angelo

Laravel 11 has introduced an array of exciting features aimed at enhancing developer productivity and application performance. Among these, the once function stands out for its simplicity and profound utility. Conceived by Taylor Otwell and Nuno Maduro, this feature offers a streamlined way to cache the results of expensive operations within the duration of a request, significantly improving efficiency.

The Power of once

At its core, the once function encapsulates the essence of performance optimization. By executing a given callback and caching its result for the remainder of the request, it ensures that subsequent calls to the same function within the same request return the cached result. This approach is particularly beneficial for data fetching operations, computations, and any process that is resource-intensive or time-consuming.

function random(): int {
    return once(function () {
        return random_int(1, 1000);
    });
}

random(); // 123
random(); // 123 (cached result)
random(); // 123 (cached result)

Unique Caching for Object Instances

A remarkable aspect of the once function is its intelligent caching mechanism when used within object instances. The cached result is unique to each object instance, thereby providing isolated and consistent data for individual object lifecycles.

class NumberService {
    public function all(): array {
        return once(fn () => [1, 2, 3]);
    }
}

$service = new NumberService;

$service->all();
$service->all(); // (cached result)

$secondService = new NumberService;

$secondService->all();
$secondService->all(); // (cached result)

Deep Diving

For those eager to delve deeper into the once function and explore its practical applications firsthand, a resource not to be missed is Luke Downing's insightful video on Laracasts. Downing, known for his expertise and engaging teaching style, offers a comprehensive tutorial on this feature in the series "What's New in Laravel 11." This episode is an excellent starting point for developers looking to harness the full potential of Laravel 11's offerings.