Last active
November 21, 2023 19:41
-
-
Save meduzen/a0b32b5e45ffdf02cee465d5da9ca90e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 $US` | |
* - if locale is 'fr': `@currency(45.49, 'eur')` outputs `45,69 €` | |
*/ | |
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 €` | |
* - 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 $US` | |
* - if locale is 'en': `@usd(45.49)` outputs `$45.69` | |
*/ | |
Blade::directive('usd', function ($expression) { | |
return "<?php echo format_currency($expression, 'usd'); ?>"; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since this week, it’s possible to rewrite this with
Number::currency
.