freshleafmedia/laravel-money-cast

A Laravel attribute cast for Money values

1.0.1 2023-09-27 11:47 UTC

This package is auto-updated.

Last update: 2024-04-27 13:17:26 UTC


README

A Money cast for Laravel models

Overview

This library provides a Laravel Attribute Cast which serialises Money instances into strings suitable for database storage.

Installation

composer require freshleafmedia/laravel-money-cast

Usage

use Freshleafmedia\MoneyCast\MoneyCast;
use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    // ...

    protected $casts = [
        'cost' => MoneyCast::class,
    ];
    
    // ...
}

Saving

$model = new MyModel();
$model->cost = new \Money\Money('100', new \Money\Currency('GBP'));
$model->save(); // 'GBP100' is persisted to the database.

Retrieving

$cost = MyModel::first()->cost; // Money\Money

$cost->getAmount() // '100'
$cost->getCurrency()->getCode() // 'GBP'

Decimal Amounts

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

Tests

Unit tests can be run via composer test

License

See LICENSE