首页 > 解决方案 > 如何在 Laravel 的模型中为所有货币字段(十进制属性)加上逗号

问题描述

我正在做一个项目,我在每个模型中都有很多十进制字段,并且想把它们都用逗号。我可以在获取时使用辅助变量或 PHP number_format()。问题是我必须为每个领域都这样做。

有什么简单的解决方案吗?

想把逗号表单
创建表单示例: 创建表单示例

索引页面/显示页面示例: 索引页面/显示页面示例

标签: laravellaravel-8

解决方案


最好的方法是使用自定义强制转换:

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


推荐阅读