The Money and Currency classes implement Laravel’s Macroable trait, allowing you to add custom functionality through macros and mixins. This powerful feature enables you to extend the package’s capabilities without modifying the source code.
Mixins allow you to add multiple methods to a class at once using a dedicated class. This is cleaner and more maintainable than defining multiple individual macros.
Here’s a comprehensive example with formatting and validation helpers:
class MoneyHelpers{ /** * Create Money from cents/minor units */ public static function cents(int $cents, Currency|string $currency): Money { return Money::ofMinor($cents, $currency); } /** * Check if amount is within range */ public function isBetween(Money $min, Money $max): bool { return $this->isGreaterThanOrEqualTo($min) && $this->isLessThanOrEqualTo($max); } /** * Format as accounting notation (negative in parentheses) */ public function formatAccounting(): string { $formatted = $this->abs()->format(); return $this->isNegative() ? "({$formatted})" : $formatted; } /** * Calculate percentage of total */ public function percentageOf(Money $total): float { if ($total->isZero()) { return 0.0; } return $this->getAmount() ->dividedBy($total->getAmount(), 4) ->multipliedBy(100) ->toFloat(); }}Money::mixin(new MoneyHelpers());// Usage$amount = Money::cents(1500, 'USD'); // $15.00$total = Money::of(100, 'USD');$amount->percentageOf($total); // 15.0
When using mixins, static methods in your mixin class become static macros on the target class, while instance methods become instance macros with access to $this.