Welcome To ITSolutionsGuides,
Lets see tutorial Laravel 11 once() Helper Function. The once() helper function in Laravel 11 is a powerful addition for executing code only once within a request lifecycle. It ensures that a particular block of code is executed only once regardless of how many times it's called within the request.With the once() helper function, you can prevent redundant operations, improve performance, and maintain cleaner code. It's especially useful when dealing with expensive operations or initializing resources that should be done only once per request. Utilize the once() helper function wisely to streamline your Laravel 11 applications and enhance efficiency.
Lets create the class using the following artisan command
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);
});
}
}
Lets create the Controller using the following artisan command, For detailed explanation aboutcreating the controller
php artisan make:controller ProductController
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);
}
}
---------------------------
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
We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.
Be the first to know about releases and tutorial news and solutions.
We care about your data in our privacy policy.
ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.
Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides