php 24 lines · 5 steps

Building a @money Blade directive in Laravel

A custom Blade directive compiles to a static call that formats amounts as localized currency.

Explained by highlit
1namespace App\Providers;
2 
3use Illuminate\Support\Facades\Blade;
4use Illuminate\Support\ServiceProvider;
5use NumberFormatter;
6 
7class BladeServiceProvider extends ServiceProvider
8{
9 public function boot(): void
10 {
11 Blade::directive('money', function (string $expression) {
12 return "<?php echo \App\\Providers\\BladeServiceProvider::formatMoney($expression); ?>";
13 });
14 }
15 
16 public static function formatMoney(int|float|string $amount, string $currency = 'USD', ?string $locale = null): string
17 {
18 $locale ??= app()->getLocale();
19 
20 $formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
21 
22 return $formatter->formatCurrency((float) $amount, $currency);
23 }
24}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Blade directives are compilers: they emit PHP source, not runtime values.
  2. 2Delegating a directive to a static method keeps generated markup tiny and testable.
  3. 3NumberFormatter with a locale gives you correct currency symbols and grouping for free.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a @money Blade directive in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code