currency format in laravel
You could create a custom Laravel directive. You still need to call that directive at every place you need it but comes with the benefit that if you ever want to change the code (e.g. replace number_format with something else) you only have to update that directive.
Example (taken from the docs and updated for your use case) (in your AppServiceProvider
boot
method):
Blade::directive('convert', function ($money) {
return "<?php echo number_format($money, 2); ?>";
});
To use it in Blade:
@convert($var)
I would most not use a "directive"... I found it cleaner to do the same logic as an accessor on the model.
public function getAmountAttribute($value)
{
return money_format('$%i', $value);
}
You can add a custom Blade directive in the boot()
method in your AppServiceProvider.php
file.
For example:
Blade::directive('money', function ($amount) {
return "<?php echo '$' . number_format($amount, 2); ?>";
});
And in your Blade file, you will just have to use @money()
like this:
@money($yourVariable)