You want a currency dropdown on a product listing page. Picking EUR should update every price, without a full reload and without turning the page into a React app. HTMX handles this with one attribute: the server renders the price list, HTMX swaps it in.

This post uses Laravel 12 with Blade, HTMX 2, and a cookie to remember the visitor's choice. The page also works with JavaScript turned off.

The idea in one picture

  1. The page renders prices in the currency from the cookie (default USD).
  2. The <select> has hx-get="/products". On change, HTMX requests the same URL with ?currency=EUR and an HX-Request: true header.
  3. The controller sees the header and returns only the price list fragment, plus a Set-Cookie for the new choice.
  4. HTMX replaces the old list with the new one.

No JSON, no client-side formatting, no state in the browser except a cookie.

Configure the rate source

Rates come from AllRatesToday: live mid-market rates for 160+ currencies. Get a free API key and add it to .env:

ALLRATES_API_KEY=art_live_xxxxxxxx 
// config/services.php 'allratestoday' => [ 'key' => env('ALLRATES_API_KEY'), ], 

A small rates service

<?php // app/Services/ExchangeRates.php namespace App\Services; use Illuminate\Http\Client\ConnectionException; use Illuminate\Http\Client\RequestException; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; class ExchangeRates { public const SUPPORTED = ['USD', 'EUR', 'GBP', 'JPY', 'CAD', 'AUD', 'CHF']; /** @return array<string, float> */ public function forBase(string $base = 'USD'): array { $key = "fx:{$base}"; try { return Cache::remember($key, now()->addMinutes(10), function () use ($base, $key) { $rates = $this->fetch($base); Cache::forever("{$key}:last_good", $rates); return $rates; }); } catch (RequestException|ConnectionException $e) { Log::warning('Exchange rate fetch failed', ['error' => $e->getMessage()]); return Cache::get("{$key}:last_good", [$base => 1.0]); } } /** @return array<string, float> */ private function fetch(string $base): array { $targets = array_values(array_diff(self::SUPPORTED, [$base])); $rows = Http::withToken(config('services.allratestoday.key')) ->timeout(5) ->get('https://allratestoday.com/api/v1/rates', [ 'source' => $base, 'target' => implode(',', $targets), ]) ->throw() // 401 bad key, 429 rate limited, 5xx: all become RequestException ->json(); $rates = [$base => 1.0]; foreach ($rows as $row) { $rates[$row['target']] = (float) $row['rate']; } return $rates; } } 

Notes:

  • The upstream API returns a JSON array of {rate, source, target, time} rows. All targets in one call count as one request, so we fetch everything we support at once.
  • Cache::remember stores nothing when the closure throws. The last_good copy without expiry is what we serve during an outage.
  • If there has never been a successful fetch, we return just the base rate. The page then shows base prices, which is better than an error page.
  • Ten minutes is a good TTL for listing pages. Rates upstream refresh about every 60 seconds.

The controller

<?php // app/Http/Controllers/ProductController.php namespace App\Http\Controllers; use App\Models\Product; use App\Services\ExchangeRates; use Illuminate\Http\Request; use Illuminate\Support\Number; class ProductController extends Controller { private const LOCALES = [ 'USD' => 'en_US', 'EUR' => 'de_DE', 'GBP' => 'en_GB', 'JPY' => 'ja_JP', 'CAD' => 'en_CA', 'AUD' => 'en_AU', 'CHF' => 'de_CH', ]; public function index(Request $request, ExchangeRates $fx) { $wanted = strtoupper((string) $request->query('currency', $request->cookie('currency', 'USD'))); $currency = in_array($wanted, ExchangeRates::SUPPORTED, true) ? $wanted : 'USD'; $rates = $fx->forBase('USD'); if (! isset($rates[$currency])) { $currency = 'USD'; // rates unavailable: fall back to base prices } $rate = $rates[$currency]; $locale = self::LOCALES[$currency]; $products = Product::orderBy('name')->get()->map(fn ($p) => [ 'name' => $p->name, 'price' => Number::currency($p->price_usd * $rate, in: $currency, locale: $locale), ]); $isFragment = $request->header('HX-Request') && ! $request->header('HX-History-Restore-Request'); $view = $isFragment ? view('products._list', compact('products', 'currency')) : view('products.index', compact('products', 'currency')); $response = response($view); if ($request->has('currency')) { $response->withCookie(cookie('currency', $currency, 60 * 24 * 365)); } return $response->header('Vary', 'HX-Request, Cookie'); } } 
// routes/web.php Route::get('/products', [App\Http\Controllers\ProductController::class, 'index'])->name('products'); 

Number::currency uses PHP's intl extension under the hood, so de_DE gives 45,99 € and ja_JP gives ¥7,558, with the correct decimals per currency. Make sure ext-intl is installed on the server.

The Vary header matters. The same URL returns either a full page or a fragment depending on HX-Request, and different prices depending on the cookie. Without Vary, a browser back button or a proxy could show the fragment as a whole page.

The Blade views

The full page includes the fragment, so there is one template for the list.

{{-- resources/views/products/index.blade.php --}} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Products</title> <script src="https://unpkg.com/htmx.org@2.0.4"></script> <style>.htmx-request #price-list { opacity: .5; transition: opacity .2s; }</style> </head> <body> <form method="get" action="{{ route('products') }}"> <label for="currency">Currency</label> <select id="currency" name="currency" hx-get="{{ route('products') }}" hx-target="#price-list" hx-swap="outerHTML" hx-push-url="true" hx-indicator="body"> @foreach (App\Services\ExchangeRates::SUPPORTED as $code) <option value="{{ $code }}" @selected($code === $currency)>{{ $code }}</option> @endforeach </select> <noscript><button type="submit">Update</button></noscript> </form> @include('products._list') </body> </html> 
{{-- resources/views/products/_list.blade.php --}} <section id="price-list"> @foreach ($products as $product) <article> <h2>{{ $product['name'] }}</h2> <p class="price">{{ $product['price'] }}</p> </article> @endforeach @if ($currency !== 'USD') <p class="note">Approximate prices at live mid-market rates. Charged in USD.</p> @endif </section> 

What each hx- attribute does:

  • hx-get: request this URL when the element's default trigger fires. For a <select>, that is change. HTMX adds the select's own name=value as a query parameter.
  • hx-target="#price-list" and hx-swap="outerHTML": replace the whole list section with the returned one.
  • hx-push-url="true": update the address bar to /products?currency=EUR, so the URL is shareable and the back button works. When HTMX restores a page from history and its cache misses, it sends HX-History-Restore-Request; that is why the controller returns the full page in that case.
  • hx-indicator="body": adds the htmx-request class during the request, which the CSS uses to fade the list.

With JavaScript disabled, the <form method="get"> and <noscript> button do a normal full-page request to the same controller, which returns the full view.

Swapping prices outside the list

Prices often appear in more than one place, such as a cart total in the header. HTMX out-of-band swaps update extra elements from the same response. Add this to the fragment:

<span id="cart-total" hx-swap-oob="true">{{ $cartTotal }}</span> 

Any element in the response with hx-swap-oob="true" replaces the element with the same id on the page. One request, several regions updated.

Testing the controller

// tests/Feature/CurrencySwitcherTest.php use App\Services\ExchangeRates; it('returns a fragment and sets the cookie for HTMX requests', function () { $this->mock(ExchangeRates::class) ->shouldReceive('forBase')->andReturn(['USD' => 1.0, 'EUR' => 0.92]); $this->get('/products?currency=EUR', ['HX-Request' => 'true']) ->assertOk() ->assertDontSee('<html', false) ->assertSee('id="price-list"', false) ->assertCookie('currency', 'EUR'); }); 

Mocking the service keeps tests offline. For the HTTP layer itself, Http::fake() with a JSON array body works the same way. The full list of response fields is in the API reference.

FAQ

Why a cookie and not the session?
A cookie works without a session store and survives logins and logouts. Laravel encrypts cookies by default, so the value cannot be tampered with in a meaningful way, and we validate it against the allowlist anyway.

Can I use hx-boost instead?
Yes. hx-boost on the form turns the GET submit into an AJAX request that swaps the <body>. It is less targeted than hx-target, but needs no HX-Request branching in the controller.

Is it bad for SEO to have prices change by cookie?
Crawlers do not keep cookies, so they index USD. If you want localized prices indexed, put the currency in the path (/eur/products) instead.

How do I avoid a request for every change while someone scrolls the select with the keyboard?
Use hx-trigger="change delay:200ms". HTMX waits until the value stops changing before it sends the request.