Home » Php » php – Using number_format method in Laravel

php – Using number_format method in Laravel

Posted by: admin April 23, 2020 Leave a comment


I am fairly new in Laravel and Blade templating.
Can anyone help show me how to do this?

I have a view like this:

@foreach ($Expenses as $Expense)
        <td>{{{ $Expense->type }}}</td>
        <td>{{{ $Expense->narration }}}</td>
        <td>{{{ $Expense->price }}}</td>
        <td>{{{ $Expense->quantity }}}</td>
        <td>{{{ $Expense->amount }}}</td>                                                            

I want the $Expense->price and$Expense->amount to be formatted.
I tried using it on the $Expense->amount as number_format($Expense->amount) but it didn’t work.

How to&Answers:

This should work :

<td>{{ number_format($Expense->price, 2) }}</td>


If you are using Eloquent, in your model put:

public function getPriceAttribute($price)
    return $this->attributes['price'] = sprintf('U$ %s', number_format($price, 2));

Where getPriceAttribute is your field on database. getSomethingAttribute.


If you are using Eloquent the best solution is:

public function getFormattedPriceAttribute()
    return number_format($this->attributes['price'], 2);

So now you must append formattedPrice in your model and you can use both, price (at its original state) and formattedPrice.