1168 1393 1237 1427 1664 1063 1384 1142 1688 1015 1020 1340 1072 1767 1799 1424 1913 1449 1044 1909 1511 1985 1531 1226 1923 1837 1585 1818 1926 1230 1837 1964 1064 1343 1753 1385 1469 1522 1789 1893 1516 1849 1377 1252 1557 1801 1992 1117 1494 1206 1291 1245 1354 1591 1294 1087 1701 1238 1639 1696 1827 1084 1511 1758 1246 1418 1515 1305 1476 1504 1856 1904 1151 1165 1819 1593 1771 1521 1174 1221 1999 1404 1230 1874 1264 1781 1878 1069 1057 1319 1013 1539 1698 1791 1643 1374 1345 1189 1037 Format monetary values by using a Money library and Laravel Blade directives | PHPnews.io

PHPnews.io

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

Written by Pascal Baljet Media - Blog / Original link on Dec. 22, 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".

pascalbaljetmedia

« 10 Lodash Features You Can Replace with ES6 - Toggle Xdebug on macOS from the terminal »