Search by

joseftraxler / laravel-money

joseftraxler

Lightweight money and currency utilities for Laravel applications.

Package info

github.com/joseftraxler/laravel-money

Homepage

Issues

pkg:composer/joseftraxler/laravel-money

Statistics

Installs: 77

Dependents: 0

Suggesters: 0

Stars: 0

v2.0.0-alpha.31 2026-12-02 23:06 UTC

README

Latest Version on Packagist Total Downloads PHP Version Laravel Version License CI

A lightweight Laravel package for working with money values, currencies, formatting, arithmetic operations, and Eloquent casts.

Laravel Money provides a small immutable Money value object with currency-aware precision handling and convenient integration for Laravel applications.

Features

  • Immutable Money value object
  • ISO 4217-style currency code validation
  • Currency-specific precision support
  • Decimal and cents-based factory methods
  • Arithmetic operations usually powered by moneyphp/money
  • Lossless allocation of amounts by ratios or into equal parts
  • Human-readable formatting using PHP intl
  • Eloquent casts for decimal and cents database columns
  • Support for fixed currency and currency-column casts
  • Laravel auto-discovery
  • Publishable configuration

Requirements

  • PHP 8.4+
  • Laravel 12+
  • PHP intl extension

Installation

Install the package via Composer:

composer require joseftraxler/laravel-money

The service provider is registered automatically through Laravel package discovery.

Configuration

The package works without publishing configuration. If you want to customize default currency or precision settings, publish the config file:

php artisan vendor:publish --tag=money-config

This publishes: config/money.php

Example configuration:

return [
    'default_currency' => 'USD', // default currency used by casts when no currency is provided
    'default_precision' => null, // null = automatically detected
    'currencies' => [
        'JPY' => ['precision' => 0],
        'BHD' => ['precision' => 3],
    ],
];

Basic usage

use JosefTraxler\LaravelMoney\Money;

$money = Money::EUR('10.45');
$money->getDecimal(); // => "10.45"
$money->getCents(); // => "1045"
$money->getCurrency()->getCode(); // => "EUR"
$money->toHumanReadable(locale: 'en_US'); // => "€10.45"

$twoPieces = $money->multiply(2)->getDecimal(); // => "20.90"

Money values can be stored in Eloquent models using casts:

$product->price = $money;
$product->save();

In Blade:

{{ $product->price }}

The examples in this README show the expected result of an expression after // =>, money as its amount and currency code (e.g. 10.45 EUR) and strings in quotes.

Currency codes are strict ISO 4217-style codes. They must contain exactly three letters.

Currency precision

Precision is resolved in this order:

  1. money.currencies.{CODE}.precision
  2. money.default_precision
  3. package-detected default precision

Precision values are validated and cached per currency for performance.

⚠️ When a decimal string value contains more fractional digits than the currency precision allows, the value is truncated to the configured precision. Float values are instead rounded to the configured precision, which compensates for binary floating-point representation (e.g. the float 1.15 is stored as 1.1499999…, so truncation would yield "1.14").

Creating money values

From decimal

use JosefTraxler\LaravelMoney\Currency;
use JosefTraxler\LaravelMoney\Money;

new Money('123.45', 'EUR');
Money::fromDecimal('123.45', 'EUR');
Money::EUR('123.45');
Money::fromDecimal('123.45', Currency::of('EUR'));

From cents

Money::fromCents(12345, 'EUR'); // => 123.45 EUR

Numeric strings are recommended

The package accepts integers, floats, and numeric strings for convenience:

Money::fromDecimal(10, 'EUR');
Money::fromDecimal(10.50, 'EUR');
Money::fromDecimal('10.50', 'EUR'); // recommended

For exact monetary input, prefer numeric strings:

Money::fromDecimal('10.50', 'EUR');

Using custom currency class/enum

You can also use a custom currency class/enum that implements JosefTraxler\LaravelMoney\Contracts\Currencyable:

enum MyCurrency: string implements JosefTraxler\LaravelMoney\Contracts\Currencyable
{
    case EUR = 'EUR';
    case USD = 'USD';

    public function getCode(): string
    {
        return $this->value;
    }
}

Money::fromDecimal('123.45', MyCurrency::EUR); // => 123.45 EUR

or some model e.g.:

use Illuminate\Database\Eloquent\Model;

class Currency extends Model implements JosefTraxler\LaravelMoney\Contracts\Currencyable
{
    protected $fillable = ['code'];

    public function getCode(): string
    {
        return $this->code;
    }
}

$currency = new Currency(['code' => 'EUR']);
Money::fromDecimal('123.45', $currency); // => 123.45 EUR

Arithmetic

Money values support common arithmetic operations.

$ten = Money::EUR('10.00');
$fiveFifty = Money::EUR('5.50');
$ten->add($fiveFifty); // => 15.50 EUR
$ten->subtract($fiveFifty); // => 4.50 EUR
$ten->multiply(2); // => 20.00 EUR
$ten->divide(2); // => 5.00 EUR
$ten->mod(Money::EUR('3.00')); // => 1.00 EUR
$fiveFifty->ratioOf($ten); // => "0.55000000000000"
Money::EUR('-10.00')->absolute(); // => 10.00 EUR
$ten->negative(); // => -10.00 EUR

Arithmetic operations are currency-aware and usually delegated to moneyphp/money. mod() returns the remainder with the sign of the dividend and ratioOf() returns a numeric-string truncated to 14 decimal places. Both accept only an amount in the same currency, otherwise they throw MoneyMismatchCurrencyException.

Division by zero

divide(), mod() and ratioOf() throw DivisionByZeroException for a zero divisor (divide() ignores digits beyond 14 decimal places, so e.g. "0.000000000000001" is zero too). All exceptions thrown when a result is undefined because of division by zero – including NoRatiosException, ZeroRatiosSumException and ZeroPartsException from allocation – implement the ZeroDivisorException interface, so a zero divisor, which is often an ordinary state of the data, can be handled without hiding other errors:

try {
    $share = $part->ratioOf($total);
} catch (ZeroDivisorException) {
    $share = null; // e.g. no income in the period yet
}

All of them also extend \InvalidArgumentException.

When a missing result is fine (e.g. to show a placeholder), call the operation through nullable(). It returns null instead of throwing when the result is undefined because of division by zero:

$share = $part->nullable()->ratioOf($total) ?? '-';
$parts = $budget->nullable()->allocate(...$ratios) ?? [];

Only ratioOf(), divide(), mod(), allocate() and allocateTo() can be called through nullable(). Other errors still throw, e.g. MoneyMismatchCurrencyException or MoneyAllocationException for a negative ratio.

Allocation

divide() rounds the result on its own, so splitting an amount into parts this way can lose minor units (e.g. 0.05 USD divided by 3 gives three times 0.01). Use allocate() or allocateTo() instead – the parts always add up exactly to the original amount and keep its currency.

// split by ratios (non-negative integers), the parts are returned in the order of the ratios
[$first, $second] = Money::USD('0.10')->allocate(1, 2); // => [0.03 USD, 0.07 USD]
$ratios = [3, 1];
Money::USD('100')->allocate(...$ratios); // => [75.00 USD, 25.00 USD]
// see the note below
Money::USD('-0.05')->allocate(1, 1, 1); // => [-0.02 USD, -0.02 USD, -0.01 USD]

// split into n equal parts
Money::USD('0.05')->allocateTo(3); // => [0.02 USD, 0.02 USD, 0.01 USD]

Leftover minor units are given to the parts with the largest fraction cut off by rounding down, on equal fractions to the first parts. Negative amounts are split as a mirror image of positive ones, so refunding an allocated amount gives each part back exactly what it got. This differs from moneyphp/money, which splits -0.05 into three parts as -0.01, -0.02, -0.02. A zero ratio gives a zero part, but at least one ratio must be positive. Decimal ratios can be converted to integers by scaling, e.g. 0.25, 0.75 to 25, 75. To keep the keys of an array of ratios, combine the keys with the result: array_combine(array_keys($ratios), $money->allocate(...$ratios)). A negative ratio or allocateTo() with a negative n throw MoneyAllocationException, which extends \InvalidArgumentException. Calling allocate() without any ratio (e.g. with ratios from an empty data set) throws its subclass NoRatiosException, calling it with all ratios zero throws ZeroRatiosSumException and calling allocateTo(0) throws ZeroPartsException (all implement ZeroDivisorException), so they can be caught separately, e.g. to split the amount equally instead:

try {
    $parts = $money->allocate(...$ratios);
} catch (NoRatiosException) {
    $parts = [];
} catch (ZeroRatiosSumException) {
    $parts = $money->allocateTo(count($ratios));
}

Comparisons

$ten = Money::EUR('10.00');
$twenty = Money::EUR('20.00');
$ten->equals($twenty); // => false
$ten->lessThan($twenty); // => true
$twenty->greaterThan($ten); // => true
$ten->compare($twenty); // => -1

Predicates are also available:

Money::EUR('10.00')->isPositive(); // => true
Money::EUR('-10.00')->isNegative(); // => true
Money::EUR('0.00')->isZero(); // => true

Formatting

In Laravel Blade, money values are automatically formatted according to the current locale.

For example, in en_US, this may render as €12.35:

{{ Money::EUR('12.35') }}

Formatting uses PHP NumberFormatter, so the intl extension is required.

You can specify a custom locale:

{{ Money::EUR('12.34')->toHumanReadable(locale: 'cs_CZ') }}

For cs_CZ, this may render as 12,34 €.

Eloquent casts

Laravel Money provides casts for storing money values as decimal or cents.

Cast definitions are specified by:

  • currency code source
    • fixed: defined by a three-letter uppercase currency code
    • dynamic: defined by a currency column name
  • amount source
    • decimal: amount in major units
    • cents: amount in minor units

Fixed currency decimal cast

Use this when the database column stores only the decimal amount and the currency is fixed:

use Illuminate\Database\Eloquent\Model;
use JosefTraxler\LaravelMoney\Money;

class Product extends Model
{
    protected function casts(): array
    {
        return [
            'price' => Money::class . ':EUR',
        ];
    }
}

Usage:

$product = Product::find(1);
$product->price->getDecimal(); // e.g. "19.99"
$product->price->getCurrency()->getCode(); // "EUR"

⚠️ When using a fixed currency cast, assigning a Money instance with a different currency throws MoneyMismatchCurrencyException.

Dynamic currency column

Use this when the amount and currency are stored in separate columns:

use Illuminate\Database\Eloquent\Model;
use JosefTraxler\LaravelMoney\Money;

class Order extends Model
{
    protected function casts(): array
    {
        return [
            'price' => Money::class . ':currency',
            'currency' => 'string',
        ];
    }
}

Usage:

$order = new Order();
$order->price = Money::USD('19.99');
$order->price->getDecimal(); // => "19.99"
$order->price->getCurrency()->getCode(); // => "USD"
$order->currency; // => "USD"

When using a dynamic currency column, the package stores the currency code automatically.

When assigning null to a money attribute using a dynamic currency column, only the amount column is set to null. The currency column is preserved intentionally, because the same currency column may be shared by multiple money attributes.

Cents storage

If you store money as cents, pass cents as the second-cast argument:

use Illuminate\Database\Eloquent\Model;
use JosefTraxler\LaravelMoney\Money;

class Payment extends Model
{
    protected function casts(): array
    {
        return [
            'amount_in_cents' => Money::class . ':currency,cents',
            'currency' => 'string',
        ];
    }
}

The example below stores 1999 in amount_in_cents and "EUR" in currency:

$payment = new Payment();
$payment->amount_in_cents = Money::EUR('19.99');
$payment->save();

When retrieving the value, the package automatically converts cents to Money using Money::fromCents().

Design notes

Strict currency codes

Currency codes are validated as three-letter ISO 4217-style codes. Whitespace is not trimmed automatically. This is intentional: invalid or unnormalized input should be handled before creating a currency value.

Precision caching

Currency precision is resolved from configuration and cached per currency code. This keeps the package efficient when many money objects are created during a request.

Decimal normalization

Money amounts are normalized according to currency precision:

Money::EUR('10'); // => 10.00 EUR
Money::JPY('10'); // => 10 JPY

Testing

Run the test suite:

composer test

Show code coverage (requires a coverage driver such as PCOV or Xdebug, the development image below has PCOV). CI requires 100 % line coverage:

composer coverage

Run static analysis:

composer stan

Check code style:

composer cs

Fix code style:

composer cs-fix

To run them without installing PHP and its extensions locally, use the development image from Dockerfile (PHP 8.5 by default, another version can be set with --build-arg PHP_VERSION=8.4):

docker build -t laravel-money-dev .
docker run --rm -u "$(id -u):$(id -g)" -v "$PWD":/app laravel-money-dev composer install
docker run --rm -u "$(id -u):$(id -g)" -v "$PWD":/app laravel-money-dev composer test
docker run --rm -u "$(id -u):$(id -g)" -v "$PWD":/app laravel-money-dev composer coverage

Contributing

Contributions are welcome.

Before opening a pull request, please ensure:

  • tests pass: composer test (they also run the PHP examples in this README and check the results after // =>)
  • code coverage stays at 100 %: composer coverage
  • code style passes: composer cs
  • static analysis passes: composer stan
  • commit messages follow Conventional Commits (e.g. feat: …, fix: …, feat!: … for breaking changes), releases and the changelog are generated from them

License

MIT License © Josef Traxler

See the LICENSE file for details.

Support