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
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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.