Laravel 10 retry() Helper Function Example Tutorial

Reading Time: 7 minutes
179 Views

Error management and retry techniques are critical in web development for creating robust and dependable apps. Laravel contains a useful retry() helper function that can be a game changer when it comes to elegantly managing and recovering from mistakes.

In this tutorial, we will walk you through the use of the retry() helper function in Laravel 10, giving you a thorough grasp of how to make the most of this functionality.

If an operation or job fails, the `retry()` utility function in Laravel is used to retry it a defined number of times. It allows you to tolerate temporary errors and automatically retry an action without having to write extensive retry logic yourself. This is especially useful for jobs that interface with external services, APIs, or that conduct actions that may fail from time to time owing to temporary difficulties.

Read More: Laravel 10 How To Encrypt Decrypt Values in Database

Let’s get started.

What is retry() Helper function in Laravel?

The retry function tries to run the specified callback until the maximum attempt threshold is reached. If the callback does not throw an exception, the value of its return value is returned. If the callback throws an exception, it will be retried automatically.

If the maximum number of attempts is exceeded, the following exception will be thrown:

Syntax

retry($maxAttempts, $callback, $sleepInSeconds = 0, $catch = null);

Explanation

  • $maxAttempts: This first parameter, $maxAttempts, plays a crucial role in determining how many times the $callback function will be retried in case it encounters failure. It sets a clear limit on the number of retry attempts, offering control over the resilience of your code.
  • $callback: The $callback parameter represents a closure or callback function where you encapsulate the code that you wish to retry. If this code block encounters exceptions or returns false, it serves as the trigger for the retry mechanism. It acts as the core functionality that you want to ensure success for.
  • $sleepInSeconds (optional): The third parameter, $sleepInSeconds, is an optional feature that enables you to specify a time delay, in seconds, between each retry attempt. This delay can be valuable when working with external services, as it helps in preventing an excessive influx of requests in a short timeframe. By default, this value is set to 0, implying no delay between retries, but you can adjust it as needed.
  • $catch (optional): The final parameter, $catch, also optional, provides a means of customizing the retry behavior based on specific exceptions. You can define an array of exception classes that, when caught during the execution of your $callback function, will trigger a retry. This feature allows for a targeted approach to error handling, enhancing the robustness of your code. In cases where this parameter is omitted, any exception thrown within the $callback will prompt a retry attempt, providing a more general approach to error recovery.

Example #1: Laravel retry() Helper Function

Here, is the first example shows you how to use retry helper function in an application.

$response = retry(3, function () {

    return Http::get('http://example.com/users');

}, 200);

This code makes up to three HTTP GET requests to ‘http://example.com/users‘ with a 200-second wait between each retry. The HTTP response is kept in the ‘$response‘ variable if the request is successful after the specified number of retries. If it still fails after three retries, any exception thrown by the HTTP request will be re-thrown, and you can handle it as needed.

Read More: Laravel 10 How To Capture Website Screenshot Tutorial

You may include a closure as the third argument to the retry function if you want to manually determine the number of milliseconds to sleep between attempts:

use Exception;
 
return retry(5, function () {
    // ...
}, function (int $attempt, Exception $exception) {

    return $attempt * 100;

});

You may use an array as the first argument to the retry function for convenience. This array will be used to calculate how many milliseconds to wait between attempts:

return retry([100, 200], function () {

    // Sleep for 100ms on first retry, 200ms on second retry...

});

Example #2: Laravel retry() Helper Function

Here, is the 2nd example shows you how to use retry helper function in an application.

$response = Http::retry(3, 200)->get('http://example.com/users');

Http::retry(3, 200)” is not a Laravel standard method. It appears to be a custom or expanded feature for the “Http” facade. This code indicates that you are attempting to configure retry behaviour before making an HTTP GET request.

You can get more details about it from it’s official documentation.

That’s it.

We hope this article helped you to learn about Laravel 10 retry() Helper Function Example Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more