laravel - 如何在 Laravel 的模型中为所有货币字段(十进制属性)加上逗号
问题描述
我正在做一个项目,我在每个模型中都有很多十进制字段,并且想把它们都用逗号。我可以在获取时使用辅助变量或 PHP number_format()
。问题是我必须为每个领域都这样做。
有什么简单的解决方案吗?
解决方案
最好的方法是使用自定义强制转换:
https://laravel.com/docs/8.x/eloquent-mutators#castables
所以例如
创建一个 ReadableNumber 类:
<?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,
[...]
];
然后在你的刀片 vues 中:
{{ $appart->value }}
将会呈现 :3 000,00
推荐阅读
- pandas - 目标 (1 &0) 列未从 str 转换为 int 类型
- r - 如何将rle与R中的金额相结合?
- json - 错误“提取中位置 0 处 JSON 中的意外令牌 P”
- docker - 如何在docker中安装conan并使用
- java - Junit 参数化数组
- css - CSS Flexbox 第一个垂直列表,然后在垂直空间用完时启动多个列
- math - SVG 背后的数学原理是什么
筛选? - python-3.x - 如何在python中按点标签一一添加颜色和图例?
- google-sheets - 如何根据另一个工作表更新 Google 工作表中的数据?
- java - 如何拆分值并保存到 Map java?