如何在 Laravel 的模型中為所有貨幣字段(十進制屬性)加上逗號 (How to put comma to all money fields (decimal attributes) in a model in Laravel)


問題描述

如何在 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 ShilMathieu Ferre)

參考文件

  1. How to put comma to all money fields (decimal attributes) in a model in Laravel (CC BY‑SA 2.5/3.0/4.0)

#laravel-8 #Laravel






相關問題

在 Laravel 的表中計算 user_id (Count user_id in a table in Laravel)

如何通過模型顯示表中的數據,自定義行除外 (How to show data from table via Model except a custom row)

如何在 Laravel 的模型中為所有貨幣字段(十進制屬性)加上逗號 (How to put comma to all money fields (decimal attributes) in a model in Laravel)

Laravel:8.x 目標類 [ArticlesController] 不存在 (Laravel:8.x Target class [ArticlesController] does not exist)

如何根據 laravel 中的一列獲取最新記錄? (How to get latest record based on one column in laravel?)

訂閱者中間件路由允許公眾查看所有受限頁面 (Subscriber middleware route allowing public to view all restricted pages)

更改徽標默認通知電子郵件 laravel 8 (change logo default notification email laravel 8)

Laravel 8 - 如果用戶有權調用路由,請簽入控制器 (Laravel 8 - Check in Controller if user has permission to call route)

laravel 微風 Multi Auth - 具有兩個不同註冊的 Admin Guard (laravel breeze Multi Auth - Admin Guard with two diffirent registration)

找不到組件的類或視圖 (Unable to locate a class or view for component)

Laravel 8 數據庫不會使用 HTML 表單更新 (Laravel 8 database won't update using HTML form)

Laravel問題從電子郵件驗證傳遞錯誤消息 (Laravel problem to pass error message from email verification)







留言討論