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 namespace App\Listeners;
How event subscribers group listeners in Laravel
event-driven
subscribers
queues
Intermediate
6 steps
rust
use std::time::Duration; #[derive(Debug, PartialEq)] pub enum ParseDurationError {
Parsing duration strings safely in Rust
parsing
error-handling
checked-arithmetic
Intermediate
8 steps
php
<?php namespace App\Services;
How user impersonation works in Laravel
authentication
authorization
session
Intermediate
8 steps
javascript
const express = require('express'); const router = express.Router(); router.get('/articles/:slug', async (req, res, next) => {
Conditional GET caching in Express
http-caching
conditional-get
routing
Intermediate
8 steps
go
package handlers import ( "net/http"
Custom validators and binding in Gin
validation
struct-tags
error-handling
Intermediate
8 steps
ruby
class ImageNormalizer ORIENTATION_TRANSFORMS = { 1 => ->(img) {}, 2 => ->(img) { img.flop },
Correcting EXIF orientation in Ruby
lookup-table
lambdas
image-processing
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.