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
php
<?php namespace App\Queue;
Deduplicating a job queue with Redis
deduplication
redis
atomicity
Advanced
8 steps
php
<?php namespace App\Providers;
Defining authorization gates in Laravel
authorization
gates
service-provider
Intermediate
6 steps
php
<?php final class TaskProgressReporter {
Tracking task progress in a JSON file
state-persistence
atomic-writes
json
Intermediate
9 steps
php
<?php namespace App\Http\Requests\DataObjects;
Typed request DTOs in Laravel
data-transfer-object
validation
immutability
Intermediate
6 steps
php
<?php namespace App\Jobs;
Rendering invoice PDFs in a Laravel queue job
queued jobs
pdf generation
file storage
Intermediate
9 steps
php
<?php namespace App\Services;
Building a valid iCalendar feed in PHP in Laravel
ical
serialization
formatting
Intermediate
8 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.