au9500 / laravel-big-decimal-cast
Custom Brick/Math BigDecimal cast for Laravel Eloquent.
Installs: 41
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/au9500/laravel-big-decimal-cast
Requires
- php: ^8.2
- brick/math: ^0.14
- illuminate/database: ^12.40
- illuminate/support: ^10.0|^11.0|^12.0
Requires (Dev)
- laravel/pint: ^1.26
- laravel/sail: ^1.48
- orchestra/testbench: ^10.8
- phpunit/phpunit: ^12.4
README
A lightweight Laravel package that provides a highly accurate BigDecimal Eloquent Cast based on brick/math. Designed for financial, scientific, or high-precision calculations where standard PHP floats fail.
๐ Features
- Casts database values into Brick\Math\BigDecimal
- Automatically converts the value back when saving
- Fully configurable precision (scale) and rounding mode
- Zero dependencies besides brick/math and Laravel support
- Auto-discovery support for Laravel
- Allows safe and precise arithmetic operations
๐ฆ Installation
Install the package via Composer:
composer require au9500/laravel-big-decimal-cast
For development, you can load the package via a local path repository inside your application composer.json.
๐ Usage
1. Add the cast to your Eloquent model
use Au9500\LaravelBigDecimalCast\Casts\BigDecimalCast;
class Product extends Model
{
protected $casts = [
'price' => BigDecimalCast::class,
];
}
2. Use it like a normal number โ but with precision
$product = Product::find(1);
// BigDecimal instance
$price = $product->price;
// Add numbers with precision
$product->price = $product->price->plus('19.99');
$product->save();
โ๏ธ Configuration
Publish the configuration file:
php artisan vendor:publish --tag=big-decimal-cast-config
This will create:
config/big-decimal-cast.php
<?php
use Brick\Math\RoundingMode;
return [
'scale' => 2,
'rounding_mode' => RoundingMode::HALF_UP,
];
Change scale globally
'scale' => 4,
Now all casts will store values with 4 decimal places.
๐ How It Works
Casting on retrieval:
return BigDecimal::of($value ?? 0);
Casting on save:
$scale = Config::get('big-decimal-cast.scale', 2);
$roundingMode = Config::get('big-decimal-cast.rounding_mode', RoundingMode::HALF_UP);
return $bigDecimal->toScale($scale, $roundingMode)->__toString();
๐งช Example Migration
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('price');
$table->timestamps();
});
Using a string or decimal column is recommended depending on precision needs.
๐ก Requirements
- PHP 8.2+
- Laravel 10 / 11 / 12
- brick/math ^0.11
๐ Why BigDecimal?
Float inaccuracies example:
0.1 + 0.2 // results in 0.30000000000000004
BigDecimal avoids this via arbitrary precision decimal arithmetic.
๐ค Contributing
- Fork this repository
- Create a feature branch
- Commit your changes
- Open a Pull Request
๐ License
This package is open-source and licensed under the MIT License.