This content originally appeared on DEV Community and was authored by Marcos Gad
The retry function attempts to execute the given callback until the given maximum attempt threshold is met. If the callback does not throw an exception, its return value will be returned. If the callback throws an exception, it will automatically be retried. If the maximum attempt count is exceeded, the exception will be thrown
function retry($times, callable $callback, $sleep = 0, $when = null);
return retry(3, function ($attempts) {
// Attempt 3 times while resting 1000ms in between attempts...
echo "Try: {$attempts} " . now()->toTimeString() . PHP_EOL;
Throw new \Exception("Failed");
}, 1000);
/*
Try: 1 10:57:48 Try: 2 10:57:49 Try: 3 10:57:50
Exception Failed
*/
with callback function true
return retry(3, function ($attempts) {
// Attempt 3 times while resting 1000ms in between attempts...
echo "Try: {$attempts} " . now()->toTimeString() . PHP_EOL;
Throw new \Exception("Failed");
}, 1000, function(){
return true;
});
/*
Try: 1 10:57:48 Try: 2 10:57:49 Try: 3 10:57:50
Exception Failed
*/
with callback function false
return retry(3, function ($attempts) {
// Attempt 3 times while resting 1000ms in between attempts...
echo "Try: {$attempts} " . now()->toTimeString() . PHP_EOL;
Throw new \Exception("Failed");
}, 1000, function(){
return false;
});
/*
Try: 1 11:08:15
Exception Failed
*/
It can be used in real life with Http client
$response = retry(3, function () {
return Http::get('http://example.com/users/1');
}, 200)
Retry in the Http client
$response = Http::retries(3, 200)->get('http://example.com/users/1');
I hope you enjoy the code.
This content originally appeared on DEV Community and was authored by Marcos Gad

Marcos Gad | Sciencx (2021-11-20T09:23:43+00:00) retry method in laravel. Retrieved from https://www.scien.cx/2021/11/20/retry-method-in-laravel/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.