Laravel: Blade directive does not work

0

Perhaps there is a better way to do the following but I would like a bit of rectoring to know what is wrong. I am trying to create a blade directive which can format weights or dollars, I mean that if we give an amount like 35000 this directive will be responsible for formatting it in the following way 35,000, to make it more readable, the problem is I'm not getting the results I expected, this is the code in the AppServiceProvider:

Blade::directive('formatodinero', function ($precio) {
        $precio = strrev($precio);
        $tamanio = strlen($precio);
        $nuevoPrecio = "";
        $j = -1;

        for($i = $tamanio; $i > 0; $i--){

            if($j % 3 == 0){
                $nuevoPrecio .= ',';

            }

            $nuevoPrecio .= $precio[$i-1];
            $j++;
        }

        return "<?php echo ($nuevoPrecio) ?>";

    });

And the way I call the directive from my view is this:

@formatodinero($propiedad->precio_venta)

Instead of printing the result formatted with commas I'm getting the string that happened to the directive itself.

    
asked by Alex VTz 12.01.2018 в 17:57
source

1 answer

1

I can help with things that I have implemented, first there is a PHP function that does what you want to achieve, number_format :

I propose two solutions, different from the directive.

1 Directly in blade podes print the following:

{{ number_format($propiedad->precio_venta, 2, ',', '.') }}

2 Create a mutator in the model of the object that has the sale price

public function getPrecioVentaAttribute($value)
{
    return number_format($value, 2, ',', '.');
}

With which when in your blade you put something like the following:

{{ $propiedad->precio_venta }} 

automatically returns the formatted value.

On the other hand to help you with the directive that you want to create, I would say that you show us with a dd () what value has the variable $ price in the directive to be able to see what is happening and put it in your question:

dd($precio);
    
answered by 12.01.2018 / 18:29
source