Skip to content

freshleafmedia/laravel-money-cast

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Laravel Money Cast

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