Skip to content

Instantly share code, notes, and snippets.

@meduzen
Last active November 21, 2023 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meduzen/a0b32b5e45ffdf02cee465d5da9ca90e to your computer and use it in GitHub Desktop.
Save meduzen/a0b32b5e45ffdf02cee465d5da9ca90e to your computer and use it in GitHub Desktop.
Laravel Blade @Currency, @usd and @Eur directives
<?php
/* Put this file in App/Helpers.php and load it in `composer.json` under `"autoload"`:
"autoload": {
"files": [
"app/helpers.php"
],
},
*/
if (! function_exists('format_currency')) {
function format_currency($amount, $currency = 'eur', $locale = null): string
{
if ($locale === null) {
$locale = app()->getLocale();
}
$euro_formatter = new NumberFormatter(app()->getLocale(), NumberFormatter::CURRENCY);
return $euro_formatter->formatCurrency($amount, $currency);
}
}
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
/**
* Blade @currency directive localizes an amount into a currency string
*
* Examples:
* - if locale is 'en': `@currency(45.49, 'usd')` outputs `$45.69`
* - if locale is 'en': `@currency(45.49, 'usd', 'fr')` outputs `45,69&nbsp;$US`
* - if locale is 'fr': `@currency(45.49, 'eur')` outputs `45,69&nbsp;€`
*/
Blade::directive('currency', function ($expression) {
return "<?php echo format_currency($expression); ?>";
});
/**
* Blade @eur directive localizes an amount in Euros
*
* Examples:
* - if locale is 'fr': `@eur(45.49)` outputs `45,69&nbsp;€`
* - if locale is 'en': `@eur(45.49)` outputs `€45.69`
*/
Blade::directive('eur', function ($expression) {
return "<?php echo format_currency($expression, 'eur'); ?>";
});
/**
* Blade @usd directive localizes an amount in US Dollars
*
* Examples:
* - if locale is 'fr': `@usd(45.49)` outputs `45,69&nbsp;$US`
* - if locale is 'en': `@usd(45.49)` outputs `$45.69`
*/
Blade::directive('usd', function ($expression) {
return "<?php echo format_currency($expression, 'usd'); ?>";
});
}
}
@meduzen
Copy link
Author

meduzen commented Nov 21, 2023

Since this week, it’s possible to rewrite this with Number::currency.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment