How to Retry HTTP Request until There is a Result in Laravel

How to retry http request unitl there is a result in Laravel? Do you know how to handle failer HTTP api response in Laravel? If you don't then this tutorial is for you. In this retry http request laravel 8 example i am going to show you that problem how you can solve.

It offen might hapen in your HTTP call that can have a high probability of failure. In such condition you can handle it with retry HTTP request. I’m sure that you don’t want that to happen. So, what would we do in such condition if happen?

As we are a Laravel developer so there is good solution for that. The retry helper function helps us in such scenario. Let's see the code:

Here’s the defination of this function.

function retry($times, callable $callback, $sleep = 0, $when = null);

 

It accepts four arguments.

  • $times - Maximum number of times we would like to attempts the callback.
  • $callback - The callback function
  • $sleep (optional) - The number of milliseconds that Laravel might wait in between attempts.
  • $when (optional) - The callback where you can specify an alternative logic

 

No we can use the retry function like that

$response = retry(3, function () {
    return Http::get('http://example.com/users/1');
}, 200)

 

Remember, if the callback throws an exception, it will automatically be retried otherwise its return value will be returned. If the maximum attempt count is exceeded, the exception will be thrown.

 

Read also: Handle Exception Error in Laravel using Rescue Helper

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js