Format monetary values by using a Money library and Laravel Blade directives

Pascal Baljet, 22 Dec 2016


For a project which has to deal with prices, we decided to use the PHP Money library. It is an implementation of Fowler's Money pattern and has great features and no dependencies. Most important, you shouldn't represent (and store) monetary values by a float. It takes away the problem of rounding errors and handles multiple currencies. Take a look at the documentation for all features and further reading.

What I want to show you is a little helper we created to echo out monetary values in this Laravel project. First we created a dedicated Service Provider so we could reuse an instance of IntlMoneyFormatter by binding the object into the container. Then we created a custom Blade directive which uses the binding to format a 'price in cents' to a representation in Euros.

<?php

namespace App;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Money\Currencies\ISOCurrencies;
use Money\Formatter\IntlMoneyFormatter;
use NumberFormatter;

class MoneyServiceProvider extends ServiceProvider
{
    public function boot()
    {
        //
    }

    public function register()
    {
        $this->app->singleton('IntlMoneyFormatter', function () {
            return new IntlMoneyFormatter(
                new NumberFormatter('nl_NL', NumberFormatter::CURRENCY),
                new ISOCurrencies
            );
        });

        Blade::directive('CentsToEuros', function ($cents) {
            return "<?php echo app('IntlMoneyFormatter')->format(\Money\Money::EUR($cents)); ?>";
        });
    }
}

Now in your Blade views you can use this directive which is very expressive and clean!

Today's price: @CentsToEuros($product->priceInCents)

Imagine the variable being 1500, this will render into "Today's price: € 15,00".