Laravel's once() method

January 24th, 2019 - 2 min read

There are times when you want to do something in your application based on a random number or event, but you always want the same outcome if that same thing happens again.

In comes once(). once is a library that does just that. Using a cache, this library will always return the same value for any value passed to it, and you can define what the response should be.

Let's look at a few examples.

class RandomClass
{
    public function getUniqueForLetter($letter)
    {
        return once(function () {
            return rand(1, 10000);
        });
    }
}

Now run the following:

$letter = 'A';

for($i = 0; $i <= 10; $i++) {
    echo (new RandomClass())->getUniqueForLetter($letter) . '<br>';
}

And you should get the same result multiple times.

once is a package from Spatie, which you can add from GitHub.