php
51 lines · 7 steps
Resilient HTTP retries with Laravel's client
A service class fetches exchange rates and retries intelligently based on the type of failure.
Explained by
highlit
1<?php
2
3namespace App\Services;
4
5use Illuminate\Http\Client\ConnectionException;
6use Illuminate\Http\Client\Request;
7use Illuminate\Http\Client\RequestException;
8use Illuminate\Http\Client\Response;
9use Illuminate\Support\Facades\Http;
10use Illuminate\Support\Facades\Log;
11
12class ExchangeRateClient
13{
14 public function latest(string $base, array $symbols): array
15 {
16 $response = Http::baseUrl(config('services.exchange.url'))
17 ->withToken(config('services.exchange.key'))
18 ->timeout(5)
19 ->acceptJson()
20 ->retry(4, 200, function (\Exception $exception, Request $request) {
21 if ($exception instanceof ConnectionException) {
22 return true;
23 }
24
25 if ($exception instanceof RequestException) {
26 Log::warning('Exchange rate request failed, retrying.', [
27 'status' => $exception->response->status(),
28 'endpoint' => $request->url(),
29 ]);
30
31 return $exception->response->status() === 429
32 || $exception->response->serverError();
33 }
34
35 return false;
36 }, throw: true)
37 ->get('/v1/latest', [
38 'base' => $base,
39 'symbols' => implode(',', $symbols),
40 ]);
41
42 return $this->normalize($response);
43 }
44
45 protected function normalize(Response $response): array
46 {
47 return collect($response->json('rates', []))
48 ->map(fn (float $rate) => round($rate, 6))
49 ->all();
50 }
51}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A retry callback lets you decide per-exception whether an error is worth retrying instead of blindly repeating every request.
- 2Distinguishing transient failures (connection drops, 429s, 5xx) from permanent ones avoids hammering an API on unrecoverable errors.
- 3Isolating the fetch and its response shaping keeps external-API quirks from leaking into the rest of the app.
Related explainers
typescript
type Event = Record<string, unknown>; interface BatcherOptions { endpoint: string;
Batching analytics events in TypeScript
batching
buffering
async
Intermediate
8 steps
php
<?php namespace App\Console\Commands;
Streaming CSV imports in Laravel
lazy-evaluation
generators
batch-processing
Intermediate
7 steps
javascript
const logger = require('./logger'); class AppError extends Error { constructor(message, statusCode = 500, details = null) {
Centralized error handling in Express
error-handling
middleware
custom-errors
Intermediate
8 steps
rust
use std::fs::File; use std::io::{self, BufWriter}; use std::path::Path;
Serializing config to JSON in Rust
serialization
serde
file-io
Intermediate
7 steps
php
<?php namespace App\Services;
Building signed, expiring download URLs in PHP in Laravel
hmac
url-signing
authentication
Intermediate
7 steps
php
<?php declare(strict_types=1);
A single-action JSON user controller in PHP
invokable-class
json-api
validation
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/resilient-http-retries-with-laravel-s-client-explained-php-9caf/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.