PHPackages                             hao-li/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. hao-li/laravel-amount

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

hao-li/laravel-amount
=====================

v2.0.1(4y ago)183.0k7[1 PRs](https://github.com/hao-li/laravel-amount/pulls)MITPHP

Since Sep 18Pushed 4y ago2 watchersCompare

[ Source](https://github.com/hao-li/laravel-amount)[ Packagist](https://packagist.org/packages/hao-li/laravel-amount)[ RSS](/packages/hao-li-laravel-amount/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (6)Dependencies (1)Versions (9)Used By (0)

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

[](#laravel-amount)

[![Total Downloads](https://camo.githubusercontent.com/cc1843b0ac621a015bee367e07f2e2f754546266d524f5660300fc00749e7923/68747470733a2f2f706f7365722e707567782e6f72672f68616f2d6c692f6c61726176656c2d616d6f756e742f642f746f74616c2e737667)](https://packagist.org/packages/hao-li/laravel-amount)[![Latest Stable Version](https://camo.githubusercontent.com/2dffa3adbff4d3dc1c58d4e453cd19c3d3df03da12fa1c51077b530a11123df7/68747470733a2f2f706f7365722e707567782e6f72672f68616f2d6c692f6c61726176656c2d616d6f756e742f762f737461626c652e737667)](https://packagist.org/packages/hao-li/laravel-amount)[![License](https://camo.githubusercontent.com/32f45d2f9f8e78e3b289ba1ba6c29fff0a5b81ae865f030b811e729623f07b01/68747470733a2f2f706f7365722e707567782e6f72672f68616f2d6c692f6c61726176656c2d616d6f756e742f6c6963656e73652e737667)](https://packagist.org/packages/hao-li/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 = $value / $this->getAmountTimes($key);
    }

    return $value;
}

public function setAttribute($key, $value)
{
    if (in_array($key, $this->getAmountFields())) {
        $value = (int) 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 "hao-li/laravel-amount:dev-master"

```

使用
--

[](#使用)

1. 在 Model 中引用 AmountTrait

```
use HaoLi\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

36

—

LowBetter than 82% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity29

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 95.5% 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.

###  Release Activity

Cadence

Every ~390 days

Recently: every ~298 days

Total

6

Last Release

1572d ago

Major Versions

v1.2.0 → v2.0.02018-11-07

### Community

Maintainers

![](https://www.gravatar.com/avatar/1500c30d9b1ae372ed0fdab777b7661795c2ff6d18a44760a38aae72d9bb924e?d=identicon)[hao li](/maintainers/hao%20li)

---

Top Contributors

[![hao-li](https://avatars.githubusercontent.com/u/11334645?v=4)](https://github.com/hao-li "hao-li (21 commits)")[![liujundezhanghao](https://avatars.githubusercontent.com/u/20275621?v=4)](https://github.com/liujundezhanghao "liujundezhanghao (1 commits)")

---

Tags

iso4217laravellaravel

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/hao-li-laravel-amount/health.svg)

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

###  Alternatives

[highideas/laravel-users-online

This package will provide an online users management.

203113.2k1](/packages/highideas-laravel-users-online)[stephenjude/filament-blog

Filament Blog Builder

20317.8k](/packages/stephenjude-filament-blog)[ralphjsmit/laravel-helpers

A package containing handy helpers for your Laravel-application.

13704.6k2](/packages/ralphjsmit-laravel-helpers)[datomatic/nova-detached-actions

A Laravel Nova tool to allow for placing actions in the Nova toolbar detached from the checkbox selection mechanism.

11229.2k](/packages/datomatic-nova-detached-actions)

PHPackages © 2026

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