0

I am trying to make a "dynamic" custom blade directive which fails because it receives the variable name and not the float. (latest laravel version)

I wanted to extend that one:

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

with an if statement if (str_ends_with($money, "00")) ... which will of cause not work, what I found out. Is there any other way to fullfill this task?

12.3400 should be displayed as 12,34

12.3401 should be displayed as 12,3401

if there is no other solution: for the moment i am using a blade component

@props(['money'])

@if (str_ends_with($money, '00'))
    {{ number_format($money, 2, ',', '') }}
@else
    {{ number_format($money, 4, ',', '') }}
@endif
  • Does this answer your question? [Remove useless zero digits from decimals in PHP](https://stackoverflow.com/questions/14531679/remove-useless-zero-digits-from-decimals-in-php) – miken32 Apr 17 '23 at 22:58
  • What does "it receives the variable name and not the float" mean? You must be calling it incorrectly. Also note `number_format()` should be passed a float, not a string. – miken32 Apr 17 '23 at 23:01
  • @miken32 i mean if you want to use `$money` outside the returned php echo you only have the variable name as string. Try to `dd($money);` , it will output "$yourVariable", not the actual value of that variable - that was my initial misstake. – Christian Wagner Apr 18 '23 at 13:08
  • Oh yes you're building a PHP statement, not running PHP commands. Whatever you put in the `@money` directive gets passed literally into to that statement without being evaluated. The assumption is that `$money` is a real variable in the scope of the blade template, so when the template is completely built and then the PHP is evaluated, it will know about it. – miken32 Apr 18 '23 at 14:44

1 Answers1

0

Try passing '$money' in str_ends_with() method:

  Blade::directive('money', function ($money) {
     return "<?php echo str_ends_with('$money', '00') ? number_format($money, 2, ',', '') : number_format($money, 4, ',', ''); ?>";
  });
Khang Tran
  • 2,015
  • 3
  • 7
  • 10
  • 1
    thanks, that now did the trick, but I had to remove the single quote in the if statement. I have tried this once, but I think i forgot to clear the views ... – Christian Wagner Apr 18 '23 at 13:01