Using number_format method in Laravel

后端 未结 4 2087
傲寒
傲寒 2021-02-06 22:52

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 ($Expen         


        
相关标签:
4条回答
  • 2021-02-06 23:07

    This should work :

    <td>{{ number_format($Expense->price, 2) }}</td>
    
    0 讨论(0)
  • 2021-02-06 23:11

    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.

    0 讨论(0)
  • 2021-02-06 23:27

    Here's another way of doing it, add in app\Providers\AppServiceProvider.php

    use Illuminate\Support\Str;
    
    ...
    
    public function boot()
    {
        // add Str::currency macro
        Str::macro('currency', function ($price)
        {
            return number_format($price, 2, '.', '\'');
        });
    }
    

    Then use Str::currency() in the blade templates or directly in the Expense model.

    @foreach ($Expenses as $Expense)
        <tr>
            <td>{{{ $Expense->type }}}</td>
            <td>{{{ $Expense->narration }}}</td>
            <td>{{{ Str::currency($Expense->price) }}}</td>
            <td>{{{ $Expense->quantity }}}</td>
            <td>{{{ Str::currency($Expense->amount) }}}</td>                                                            
        </tr>
    @endforeach
    
    0 讨论(0)
  • 2021-02-06 23:29

    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.

    0 讨论(0)
提交回复
热议问题