DEV Community

Cover image for Laravel blade directive for money format
Ariel Mejia
Ariel Mejia

Posted on

Laravel blade directive for money format

Create a service provider for custom blade directives:

php artisan make:provider BladeServiceProvider
Enter fullscreen mode Exit fullscreen mode

Register the new service provider:

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

$providers = [
    ...
    App\Providers\BladeServiceProvider::class,
];
Enter fullscreen mode Exit fullscreen mode

Add the directive in blade service provider:

Go to "app/Providers/BladeServiceProvider" in the boot method:

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

It use the Blade facade, with "directive" method the first argument is the name of the created directive in this case "money", then the second argument is a callback

The "$money" variable that represents the value pass to the directive, then it returns the value formatted using the "number_format" method.

Use the new money directive:

In any blade file:

@money($value)
Enter fullscreen mode Exit fullscreen mode

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.

Latest comments (5)

Collapse
 
geekfahim profile image
Fahim Ahmed • Edited

Instead of ( return "<?php echo number_format($money, 2); ?>";) this

you can do (return "<?php echo money_format($value); ?>";)

N.B: Ignore the brackets.

Collapse
 
rintoug profile image
Rinto George

Don't forget to clear your view cache

Collapse
 
foxbille profile image
Foxbille

Thank you, very useful !!

Collapse
 
arielmejiadev profile image
Ariel Mejia

Thanks for the comment!

Collapse
 
rodrigoespinozadev profile image
Rodrigo Espinoza

Thank you!