giordanolima/decimal-mutators

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

1.1.4 2020-10-21 19:46 UTC

This package is auto-updated.

Last update: 2024-04-22 02:59:19 UTC


README

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