Laravel blade directive for money format

Ariel Mejia

June 11th, 2020 - 1 min read

Create a new service provider:

php artisan make:provider BladeServiceProvider

Register the new service provider:

In config/app.php add the new blade service provider in providers array:

$providers = [
    ...
    App\Providers\BladeServiceProvider::class,
];

Add the directive in the blade service provider:

In app/Providers/BladeServiceProvider add this code inside the boot method:

Blade::directive('money', function ($money) {
    return "<?php echo number_format($money, 2); ?>";
});

It uses the Blade facade directive method, the first argument is the name of the directive in this case money, the second argument is a callback

The $money variable is the value pass through the directive, then it returns the value formatted using the php function number_format.

Use the new money directive:

In any blade file:

@money($value)

Notes:

I think that this directives are a great place to make some tricky formatting, but if you want to add more logic, maybe a best way to add this is with a model method or an action class.

Thanks for reading!


Ariel Mejia Illustration

Ariel Mejia

Laravel Senior Developer

Engineer with 7+ years of experience working in backend & frontend technologies
Open Source Maintainer of packages for Laravel community.

Stay up with Laravel

Sign up & get tips and tricks

You'll get monthly updates regarding my most recent articles and products.