PHPackages                             gallop-yd/laravel-amount - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. gallop-yd/laravel-amount

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

gallop-yd/laravel-amount
========================

1122PHP

Since Feb 28Pushed 7y agoCompare

[ Source](https://github.com/GallopYD/laravel-amount)[ Packagist](https://packagist.org/packages/gallop-yd/laravel-amount)[ RSS](/packages/gallop-yd-laravel-amount/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

laravel-amount
==============

[](#laravel-amount)

[![Total Downloads](https://camo.githubusercontent.com/1fd67f86fa3016b3c622f3d3df3ae4bfd6278842b2fcd9500ea4289c24c94381/68747470733a2f2f706f7365722e707567782e6f72672f67616c6c6f702d79642f6c61726176656c2d616d6f756e742f642f746f74616c2e737667)](https://packagist.org/packages/gallop-yd/laravel-amount)[![Latest Stable Version](https://camo.githubusercontent.com/72c61fa7af761513d65b4a4cd37874fe27f0eb2e18aa7151ad1ca36096804f24/68747470733a2f2f706f7365722e707567782e6f72672f67616c6c6f702d79642f6c61726176656c2d616d6f756e742f762f737461626c652e737667)](https://packagist.org/packages/gallop-yd/laravel-amount)[![License](https://camo.githubusercontent.com/5b751c9b7cd753b98e55d4b434cdda17dcca1957ff3aadf3d599d408ea84197f/68747470733a2f2f706f7365722e707567782e6f72672f67616c6c6f702d79642f6c61726176656c2d616d6f756e742f6c6963656e73652e737667)](https://packagist.org/packages/gallop-yd/laravel-amount)

背景
--

[](#背景)

系统中涉及到金额的字段，View 层表现的时候一般都是以**元**为单位使用小数形式展示，不过 Domain 层存储时从空间、性能、容错角度出发，经常以**分**为单位，用整型来存储。

在 Lavarel 中，可以在 Model 中添加属性方法进行转换

```
public function getAmountAttribute($value)
{
    return $value / 100;
}

public function setAmountAttribute($value)
{
    $this->attributes['amount'] = (int)($value * 100);
}
```

不过涉及金额的字段比较多时就需要定义很多相同逻辑的函数，本项目即将该逻辑抽出为 Trait，简化金额字段相关的处理。

> 除了金额外，小数位数固定的**面积**、**长度**等场景使用起来也很方便。

原理
--

[](#原理)

将转换逻辑封装在 AmountTrait 中，覆写 Model 类的 getMutatedAttributes, mutateAttributeForArray, getAttributeValue 及 setAttribute 方法，当访问相关字段时自动进行转换处理。

```
public function getMutatedAttributes()
{
    $attributes = parent::getMutatedAttributes();

    return array_merge($attributes, $this->getAmountFields());
}

protected function mutateAttributeForArray($key, $value)
{
    return (in_array($key, $this->getAmountFields()))
        ? $value / $this->getAmountTimes($key)
        : parent::mutateAttributeForArray($key, $value);
}

public function getAttributeValue($key)
{
    $value = parent::getAttributeValue($key);
    if (in_array($key, $this->getAmountFields())) {
        $value = bcdiv($value,$this->getAmountTimes($key),2);
    }
    return $value;
}

public function setAttribute($key, $value)
{
    if (in_array($key, $this->getAmountFields())) {
        if (function_exists('bcmul')) {
            $value = bcmul($value, $this->getAmountTimes($key));
        } else {
            $value = round($value * $this->getAmountTimes($key));
        }
    }
    parent::setAttribute($key, $value);
}

public function getAmountFields()
{
    return (property_exists($this, 'amountFields')) ? $this->amountFields : [];
}

public function getAmountTimes($key)
{
    $ret = 100;

    if (property_exists($this, 'amountTimes')) {
        if (is_array($this->amountTimes) && array_key_exists($key, $this->amountTimes)) {
            $ret = $this->amountTimes[$key];
        } elseif (is_numeric($this->amountTimes)) {
            $ret = $this->amountTimes;
        }
    }

    return $ret;
}
```

依赖
--

[](#依赖)

Laravel &gt;= 5.2

安装
--

[](#安装)

```
composer require "gallop-yd/laravel-amount:dev-master"

```

使用
--

[](#使用)

1. 在 Model 中引用 AmountTrait

```
use GallopYD\LaravelAmount\Traits\AmountTrait;
```

2. 使用 AmountTrait

```
use AmountTrait;
```

3. 定义金额字段（本例中为 amount）

```
protected $amountFields = ['amount'];
```

4. 通过 `$amountTimes` 指定金额字段的倍数（可选，默认 100）

- 各金额字段使用相同的倍数 ```
    protected $amountTimes = 100;
    ```
- 不同金额字段设置不同倍数 ```
    protected $amountTimes = [
        'amount' => 100,
    ]
    ```

5. 完成

之后读取 amount 字段时，该字段的内容会自动从数据库的**分**转换为**元**，向其赋值时反之从**元**转换为**分**。

FAQ
---

[](#faq)

### 和别的 trait 中方法冲突

[](#和别的-trait-中方法冲突)

以 setRawAttributes 为例（此为之前方案，目前并未覆写此方法，仅为举例，其他方法原理相同）

1. 将冲突的方法分别重命名

```
use AmountTrait, BTrait {
    AmountTrait::setRawAttributes as amountTraitSetRawAttributes;
    BTrait::setRawAttributes as BTraitSetRawAttributes;
}
```

2. 在 Model 中定义该冲突的方法，根据情况分别调用别名方法

```
public function setRawAttributes(array $attributes, $sync = false)
{
    $this->BTraitSetRawAttributes($attributes, $sync);
    $attributes = $this->getAttributes();
    $this->amountTraitSetRawAttributes($attributes, $sync);
}
```

> 注意这里 $attributes 可能已被改变，所以再次使用时要重新取得最新值

###  Health Score

21

—

LowBetter than 19% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/88c2a8e9be2e5a4d6964c31f9e57f282bf7419f70424e215fd51e77032572fe8?d=identicon)[GallopYD](/maintainers/GallopYD)

---

Top Contributors

[![GallopYD](https://avatars.githubusercontent.com/u/26155034?v=4)](https://github.com/GallopYD "GallopYD (3 commits)")

### Embed Badge

![Health badge](/badges/gallop-yd-laravel-amount/health.svg)

```
[![Health](https://phpackages.com/badges/gallop-yd-laravel-amount/health.svg)](https://phpackages.com/packages/gallop-yd-laravel-amount)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
