A Money cast for Laravel models
This library provides a Laravel Attribute Cast which serialises Money instances into strings suitable for database storage.
composer require freshleafmedia/laravel-money-cast
use Freshleafmedia\MoneyCast\MoneyCast;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
// ...
protected $casts = [
'cost' => MoneyCast::class,
];
// ...
}
$model = new MyModel();
$model->cost = new \Money\Money('100', new \Money\Currency('GBP'));
$model->save(); // 'GBP100' is persisted to the database.
$cost = MyModel::first()->cost; // Money\Money
$cost->getAmount() // '100'
$cost->getCurrency()->getCode() // 'GBP'
Note that due to the way moneyphp/money works amounts are in the smallest unit.
For example GBP100
=> £1.00, USD100
=> $1.00, JPY100
=> ¥100, etc.
See the Formatting section of the moneyphp docs for details
Unit tests can be run via composer test
See LICENSE