ibrand / laravel-currency-format
iBrand 社群服务器。
v1.0.0
2018-12-27 13:09 UTC
Requires
- php: >=7.0
Requires (Dev)
- orchestra/database: ~3.5
- orchestra/testbench: ~3.5
- phpunit/phpunit: ~6.0
This package is auto-updated.
Last update: 2024-09-10 17:18:05 UTC
README
###laravel-currency-format
Laravel 针对实际需求且易于扩展的数字和金额格式化组件
基于业务需求,需要将数字和金额格式化以便于前端展示,Laravel Eloquent 官方提供了修改器,例如将分
为单位的amount
字段转换为元
:
public function getAmountAttribute() { return number_format($this->value, 2, '.', ''); }
特性
- 自定义需要转换的字段
- 使用
Trait
即用即装 FormatContract
方便扩展开发- 支持
toArray
数组化
安装
composer require ibrand/laravel-currency-format
使用
- 定义
Eloquent Model
模型 - 引用格式化
Trait
模型:use iBrand\Currency\Format\HasFormatAttributesTrait
- 自定义格式化字段:
protected $format_attributes
就这么简单
<?php /* * This file is part of ibrand/laravel-currency-formatter. * * (c) iBrand <https://www.ibrand.cc> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace iBrand\Currency\Format; use iBrand\Currency\Format\HasFormatAttributesTrait; use Illuminate\Database\Eloquent\Model; class Order extends Model { use HasFormatAttributesTrait;//引用格式化Trait protected $guarded = ['id']; protected $format_attributes = ['total', 'items_total'];//自定义需要格式化的字段,就是这么简单 public function __construct(array $attributes = []) { parent::__construct($attributes); $this->setTable(config('ibrand.app.database.prefix', 'ibrand_').'order'); } }
例如访问
格式化total
属性,可以通过$order->display_total
来实现。