問題描述
如何在 Laravel 的模型中為所有貨幣字段(十進制屬性)加上逗號 (How to put comma to all money fields (decimal attributes) in a model in Laravel)
我正在開展一個項目,我在每個模型中都有很多十進製字段,並且希望將所有這些字段都用逗號分隔。我可以在獲取時使用輔助變量或 PHP number_format()
。問題是我必須對每個字段都這樣做。
有什麼簡單的解決方案嗎?
參考解法
方法 1:
The best way to do this is to use custom casts :
https://laravel.com/docs/8.x/eloquent‑mutators#castables
So for example
create a ReadableNumber class :
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class ReadableNumber implements CastsAttributes
{
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
* @return string
*/
public function get($model, $key, $value, $attributes)
{
return number_format($value, 2, ',', ' ');
}
public function set($model, $key, $value, $attributes)
{
return str_replace(" ", "", str_replace(",", ".", $value));
}
}
protected $casts = [
'size' => ReadableNumber::class,
'rate' => ReadableNumber::class,
'value' => ReadableNumber::class,
[...]
];
then in your blade vues :
{{ $appart‑>value }}
will show : 3 000,00
(by Sumon Chandra Shil、Mathieu Ferre)