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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Blade directives are compilers: they emit PHP source, not runtime values.
- 2Delegating a directive to a static method keeps generated markup tiny and testable.
- 3NumberFormatter with a locale gives you correct currency symbols and grouping for free.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 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
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
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/building-a-money-blade-directive-in-laravel-explained-php-e429/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.