How to use retry() in Laravel
In real-world applications, failures are inevitable — whether it's a flaky API, a temporary DB lock, or a slow external service. That's where Laravel’s retry() helper shines.
If you are unsure about any function, feature or any third-party service and there is a chance of temporary failure, then in such cases we normally write heavy code-level logic to handle such scenarios or sometimes we write nested try catch blocks which becomes very complex and not maintainable. In such cases we can make use of retry() method.
This method is very handy, easy to implement and maintain. You just simply need to pass the threshold limit, that how many times the code block needs to be retried and that's it. In case of any failure it will retry until the threshold limit exceeds. If it still fails then it will simply throw the error and on success, it will simply return the value defined on the code block.
In this blog we will learn about how to use retry() method in Laravel to handle errors gracefully.
It comes in particularly handy when dealing with:
- External APIs
- Payment gateways
- Jobs & Queues
- Network or DB timeouts
🛠 Syntax of retry() :
retry(int $times, callable $callback, int $sleep = 0, callable $when = null)
Parameters:
- $times: Number of attempts (including the first one)
- $callback: The code to run
- $sleep: (Optional) Delay in milliseconds between attempts
- $when: (Optional) Callback to decide whether to retry or not based on the exception
✅ Basic Example: Retry an API Call
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; $response = retry(3, function () { return Http::get('https://thedevnerd.com/sample/data'); }, 100);
✅ 3. Downloading or Uploading Files to S3 / Cloud Storage
retry(3, function () use ($filePath) { Storage::disk('s3')->put('uploads/' . basename($filePath), fopen($filePath, 'r+')); }, 500);
✅ 6. Running Artisan Commands or Database Migrations in CI/CD
retry(3, function () { Artisan::call('migrate', ['--force' => true]); }, 1000);
⚠️ What Happens if All Attempts Fail?
public function index(){ try { $data = retry(3, function() { return Http::get('https://thedevnerd.com/sample/data'); }, 100); } catch (\Exception $e) { // Handle failure gracefully Log::error('Operation failed after retries: ' . $e->getMessage()); } }
🔒 Things to keep in mind while using retry():
Always use retry() when:
- The operation can safely run multiple times.
- You want to improve reliability with external services/3rd party Api's.
- You want to handle temporary errors gracefully.
- Let's see with some example of how can you use it.