How to Use Once() Helper Function in Laravel 11

In this article, I will demonstrate how to utilize the once() helper function in Laravel 11 framework. In Laravel 11, a new helper function called once() has been introduced. It guarantees that you receive the same value regardless of how many times you invoke an object method.

The once() function proves to be beneficial when there's a need to ensure that a particular segment of code executes only once.

So, let's see how to use the once() helper function in laravel 11, laravel 11 helper function, and how to create a helper function in laravel 11, once() helper function.

First, let's create a simple OnceTest class with two methods to generate random strings. One method will return a random 6-character string, while the other will utilize the once helper function.

Run the following command to generate a new class:

php artisan make:class OnceRandom

Inside app/OnceRandom.php, update the code as follows:

<?php
  
namespace App;
  
use Illuminate\Support\Str;
  
class OnceRandom
{
    /**
     * Generate a random string.
     *
     * @return string
     */
    public function generateRandom()
    {
        return Str::random(6);
    }
      
    /**
     * Generate a random string using once helper function.
     *
     * @return string
     */
    public function generateRandomOnce()
    {
        return once(function () {
            return Str::random(6);
        });
    }
}

Now, let's use this class in a function like the code below:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\OnceRandom;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $obj = new OnceRandom();
  
        $random1 = $obj->generateRandom();
        $random2 = $obj->generateRandom();
  
        $randomOnce1 = $obj->generateRandomOnce();
        $randomOnce2 = $obj->generateRandomOnce();
        $randomOnce3 = $obj->generateRandomOnce();
  
        dump($random1, $random2, $randomOnce1, $randomOnce2, $randomOnce3);
    }
}

You will receive the following output:

"4xYJKy"
"tf0X9q"
  
"efNBkA"
"efNBkA"
"efNBkA"

This output demonstrates that the first two random strings are different each time they are generated, while the three instances of the random string generated using the once() helper functions are the same.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS