LaravelPackages.net
Acme Inc.
Toggle sidebar
giordanolima/decimal-mutators

Add a short way to create accessors and mutators for decimal fields

1.088
13
1.1.4
About giordanolima/decimal-mutators

giordanolima/decimal-mutators is a Laravel package for add a short way to create accessors and mutators for decimal fields. It currently has 13 GitHub stars and 1.088 downloads on Packagist (latest version 1.1.4). Install it with composer require giordanolima/decimal-mutators. Discover more Laravel packages by giordanolima or browse all Laravel packages to compare alternatives.

Last updated

Latest Stable Version Total Downloads License StyleCI

Decimal Mutators for Laravel

Decimal Mutators provides a short way to create accessors and mutators for decimal fields.

Install

Install package through Composer

composer require giordanolima/decimal-mutators

Usage

You should use it as a trait of your model, and declare which fields you want to apply the mutators:

use Illuminate\Database\Eloquent\Model,
    GiordanoLima\DecimalMutators\DecimalMutators;
class MyModel extends Model
{
	use DecimalMutators;

	protected $decimalsFields = [
            'decimal_field_1',
            'decimal_field_2',
            'decimal_field_3',
            'decimal_field_4'
        ];

}

By default, the trait will get the data from database and will replace "," (comma) as thousand separator to ""(blank) and will replace "." (dot) as decimal separator to "," (comma). The behavior will be like this:

$myModel = MyModel::find(1);
$myModel->decimal_field_1 = '200,00';
$myModel->save(); // It will store as 200.00

$myModel = MyModel::find(1);
echo $myModel->decimal_field_1; // Will print 200,00

By default, it gonna be used 2 for decimal points... If you need change it, you can set the option:

protected $decimalsOptions = [
    "decimals" => 4, // now, the fields will be stored and printed with 4 decimals point
];

If you want to replace defaults separators, you can replace with:

protected $decimalsOptions = [
    "setDecimalsFrom" => ",",
    "setDecimalsTo" => ".",
    "setThounsandFrom" => ".",
    "setThounsandTo" => "",
    "getDecimalsFrom" => ".",
    "getDecimalsTo" => ",",
    "getThounsandFrom" => ",",
    "getThounsandTo" => "",
];

You can disable the mutators:

MyModel::$disableGetMutator = true;
echo $myModel->decimal_field_1; // Will print 200.00
MyModel::$disableGetMutator = false;
echo $myModel->decimal_field_1; // Will print 200,00
MyModel::$disableSetMutator = true;
$myModel->decimal_field_1 = '200,00';
$myModel->save(); // It will store as 200,00
MyModel::$disableSetMutator = false;
$myModel->decimal_field_1 = '200,00';
$myModel->save(); // It will store as 200.00

Star History Chart