Laravel blade directive for money format

Ariel Mejia - Jun 11 '20 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .