Laravel 11 once() Helper Function Example

By Hardik Savani April 16, 2024 Category : Laravel

Laravel 11 once helper function

In this short post, I will show you how to use once() helper function in laravel 11 framework.

In Laravel 11, a new helper function called `once()` has been added. It ensures that you get the same value no matter how many times you call an object method. The `once()` function is valuable when you need to guarantee that a certain piece of code executes only once.

Let's see how to use it with the example code:

First, we will create a simple OnceTest class and create two methods to generate a random string. One will simply return a random 10 characters, and for another function we will use the once helper function it.

Run the following command to create a new class:

php artisan make:class OnceTest

app/OnceTest.php

<?php
  
namespace App;
  
use Illuminate\Support\Str;
  
class OnceTest
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function random()
    {
        return Str::random(10);
    }
      
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function randomOnce()
    {
        return once(function () {
            return Str::random(10);
        });
    }
}

Now, we will simply use that class with a function like the code below:

app/Http/Controllers/ProductController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\OnceTest;
  
class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $obj = new OnceTest();
  
        $random1 = $obj->random();
        $random2 = $obj->random();
  
        $randomOnce1 = $obj->randomOnce();
        $randomOnce2 = $obj->randomOnce();
        $randomOnce3 = $obj->randomOnce();
  
        dump($random1, $random2, $randomOnce1, $randomOnce2, $randomOnce3);
    }
}

You will get the following output:

"2XxMsJ4Jyo" // app/Http/Controllers/ProductController.php:28
"thfl0Xk5Rq" // app/Http/Controllers/ProductController.php:28
  
"eGfSNbJbOD" // app/Http/Controllers/ProductController.php:28
"eGfSNbJbOD" // app/Http/Controllers/ProductController.php:28
"eGfSNbJbOD" // app/Http/Controllers/ProductController.php:28

I hope it can help you...

Shares