### Install and Publish Laravel Money Package Source: https://context7.com/akaunting/laravel-money/llms.txt Install the package via Composer and publish the configuration file to customize supported currencies and defaults. ```bash composer require akaunting/laravel-money php artisan vendor:publish --tag=money ``` -------------------------------- ### Install Laravel Money Package Source: https://github.com/akaunting/laravel-money/blob/master/README.md Use Composer to install the package. This command adds the package as a dependency to your Laravel project. ```bash composer require akaunting/laravel-money ``` -------------------------------- ### Locale Management Source: https://context7.com/akaunting/laravel-money/llms.txt Allows setting and getting the static locale for money formatting. This affects methods like `formatForHumans` when no explicit locale is provided. ```APIDOC ## Locale Support — `setLocale` / `getLocale` The service provider automatically sets the locale from Laravel's translator. You can override it statically for locale-sensitive formatting methods. ### Method Signature ```php Money::setLocale(string $locale) Money::getLocale(): string ``` ### Description - `setLocale`: Sets the static locale for all subsequent money formatting operations that do not specify an explicit locale. - `getLocale`: Retrieves the currently set static locale. ### Example ```php use Akaunting\Money\Money; Money::setLocale('de_DE'); echo Money::getLocale(); // "de_DE" $money = Money::EUR(123456); // formatForHumans respects the static locale when no locale argument is passed echo $money->formatForHumans(); // "€1.234,56" (de_DE separators) echo $money->formatForHumans('en_US'); // "$1,234.56" (explicit override) // Reset to default Money::setLocale('en_GB'); ``` ``` -------------------------------- ### Set and Get Locale for Money Formatting Source: https://context7.com/akaunting/laravel-money/llms.txt Override the default locale for money formatting methods. The locale can be set statically and retrieved using `getLocale()`. Formatting methods respect this static locale unless an explicit locale argument is provided. ```php use Akaunting\Money\Money; Money::setLocale('de_DE'); echo Money::getLocale(); // "de_DE" $money = Money::EUR(123456); // formatForHumans respects the static locale when no locale argument is passed echo $money->formatForHumans(); // "€1.234,56" (de_DE separators) echo $money->formatForHumans('en_US'); // "$1,234.56" (explicit override) // Reset to default Money::setLocale('en_GB'); ``` -------------------------------- ### Basic Money Instantiation and Formatting Source: https://github.com/akaunting/laravel-money/blob/master/README.md Demonstrates how to create Money objects using static methods or constructors and display them. The 'true' parameter enables conversion. ```php use Akaunting\Money\Currency; use Akaunting\Money\Money; echo Money::USD(500); // '$5.00' unconverted echo new Money(500, new Currency('USD')); // '$5.00' unconverted echo Money::USD(500, true); // '$500.00' converted echo new Money(500, new Currency('USD'), true); // '$500.00' converted ``` -------------------------------- ### Publish Configuration File Source: https://github.com/akaunting/laravel-money/blob/master/README.md Publish the package's configuration file using the Artisan command. This allows you to customize currency settings. ```bash php artisan vendor:publish --tag=money ``` -------------------------------- ### Instantiate and Use Currency Class Source: https://context7.com/akaunting/laravel-money/llms.txt The `Currency` class represents ISO 4217 currency metadata. It can be instantiated statically (e.g., `Currency::USD()`) or with `new Currency('CODE')`. Demonstrates retrieving currency details and performing equality checks. ```php use Akaunting\Money\Currency; $usd = Currency::USD(); // same as new Currency('USD') $eur = new Currency('EUR'); echo $usd->getCurrency(); // "USD" echo $usd->getName(); // "US Dollar" echo $usd->getCode(); // 840 echo $usd->getRate(); // 1.0 (default, override in config) echo $usd->isSymbolFirst(); // true echo $usd->render(); // "USD (US Dollar)" echo (string) $usd; // "USD (US Dollar)" // Equality check $usd->equals(Currency::USD()); // true $usd->equals(Currency::EUR()); // false // Serialisation $usd->toArray(); // ['USD' => ['name' => 'US Dollar', 'code' => 840, 'rate' => 1, 'precision' => 2, // 'subunit' => 100, 'symbol' => '$', 'symbol_first' => true, // 'decimal_mark' => '.', 'thousands_separator' => ',', // 'prefix' => '$', 'suffix' => '']] echo $usd->toJson(); // JSON of the above array ``` -------------------------------- ### Static Currency Factory Methods for Money Source: https://context7.com/akaunting/laravel-money/llms.txt Instantiate `Money` objects using static methods corresponding to ISO 4217 currency codes. This simplifies creating currency instances without manually instantiating `Currency`. ```php use Akaunting\Money\Money; echo Money::USD(500); // "$5.00" (500 cents) echo Money::USD(5.00, true); // "$5.00" (5.00 dollars → converted to 500 cents) echo Money::EUR(1000); // "€10.00" echo Money::GBP(750); // "£7.50" echo Money::JPY(500); // "¥500" (JPY has precision=0, subunit=1) echo Money::BHD(1000); // "BD1.000" (BHD has precision=3) ``` -------------------------------- ### Create Currency Object with Helper Function Source: https://context7.com/akaunting/laravel-money/llms.txt Use the global `currency()` helper to create a `Currency` object. It falls back to the default currency if no argument is provided. Demonstrates accessing currency properties like symbol, precision, and subunit. ```php $usd = currency('USD'); echo $usd; // "USD (US Dollar)" echo $usd->getSymbol(); // "$" echo $usd->getPrecision(); // 2 echo $usd->getSubunit(); // 100 echo $usd->getDecimalMark(); // "." echo $usd->getThousandsSeparator(); // "," echo $usd->getPrefix(); // "$" echo $usd->getSuffix(); // "" $eur = currency('EUR'); echo $eur->getPrefix(); // "€" echo $eur->getSuffix(); // "" // Currency with suffix symbol (e.g., SEK) $sek = currency('SEK'); echo $sek->getPrefix(); // "" echo $sek->getSuffix(); // " kr" ``` -------------------------------- ### Construct Money Instance Source: https://context7.com/akaunting/laravel-money/llms.txt Create a `Money` instance using the constructor, which accepts an amount, a `Currency` object, and an optional conversion flag. The amount can be an integer, float, string, or callable. ```php use Akaunting\Money\Currency; use Akaunting\Money\Money; // 500 cents (stored as-is, no conversion) $price = new Money(500, new Currency('USD')); echo $price; // "$5.00" // 5.00 dollars → converted to 500 cents internally $price = new Money(5.00, new Currency('USD'), true); echo $price; // "$5.00" // Parsed from a formatted string $price = new Money('$1,234.56', new Currency('USD')); echo $price->getAmount(); // 123456.0 (stored in cents, float) // Amount from a callable $price = new Money(fn() => 999, new Currency('EUR')); echo $price; // "€9.99" ``` -------------------------------- ### Money and Currency Helper Functions Source: https://github.com/akaunting/laravel-money/blob/master/README.md Provides convenient global helper functions for creating Money and Currency instances. These simplify common instantiation tasks. ```php money(500) money(500, 'USD') currency('USD') ``` -------------------------------- ### Static Currency Factory Methods Source: https://context7.com/akaunting/laravel-money/llms.txt Static methods for creating Money instances for specific currencies. Any ISO 4217 currency code can be called as a static method on Money. ```APIDOC ## Money::{CURRENCY_CODE}($amount, bool $convert = false) ### Description Static currency factory methods. Any ISO 4217 currency code can be called as a static method on `Money` to create an instance without manually instantiating `Currency`. Over 150 currencies are supported (AED, AFN, ALL, … ZWL). ### Parameters #### Path Parameters - **$amount** (int|float|string|callable) - Required - The monetary amount. - **$convert** (bool) - Optional - Whether to convert the amount from major unit to subunit. ### Request Example ```php use Akaunting\Money\Money; echo Money::USD(500); // "$5.00" (500 cents) echo Money::USD(5.00, true); // "$5.00" (5.00 dollars → converted to 500 cents) echo Money::EUR(1000); // "€10.00" echo Money::GBP(750); // "£7.50" echo Money::JPY(500); // "¥500" (JPY has precision=0, subunit=1) echo Money::BHD(1000); // "BD1.000" (BHD has precision=3) ``` ``` -------------------------------- ### Money Serialization Methods Source: https://context7.com/akaunting/laravel-money/llms.txt Demonstrates how Money and Currency objects can be serialized into arrays or JSON. These objects implement `Arrayable`, `Jsonable`, and `JsonSerializable` for seamless integration with API responses. ```php use Akaunting\Money\Money; use Akaunting\Money\Currency; $money = Money::USD(4999); print_r($money->toArray()); // ['amount' => 4999, 'value' => 49.99, 'currency' => Currency object] echo $money->toJson(); // {"amount":4999,"value":49.99,"currency":{"USD":{"name":"US Dollar","code":840,...}}} // Works naturally in Laravel API resources / response()->json() return response()->json(['price' => $money]); // auto-serialized // Currency serialization $usd = new Currency('USD'); echo $usd->toJson(); // {"USD":{"name":"US Dollar","code":840,"rate":1,"precision":2,"subunit":100, // "symbol":"$","symbol_first":true,"decimal_mark":".","thousands_separator":",", // "prefix":"$","suffix":""}} ``` -------------------------------- ### Configure Default Currencies and Settings Source: https://context7.com/akaunting/laravel-money/llms.txt Customize supported currencies and default settings by editing the `config/money.php` file. This includes setting fallback currencies and conversion behaviors. ```php // config/money.php return [ 'defaults' => [ 'currency' => env('MONEY_DEFAULTS_CURRENCY', 'USD'), // fallback currency 'convert' => env('MONEY_DEFAULTS_CONVERT', false), // auto-convert from major to subunit ], 'currencies' => [ 'USD' => [ 'name' => 'US Dollar', 'code' => 840, 'precision' => 2, 'subunit' => 100, 'symbol' => '$', 'symbol_first' => true, 'decimal_mark' => '.', 'thousands_separator' => ',', ], // add or override currencies here... ], ]; ``` -------------------------------- ### Global Helper Function for Money Objects Source: https://context7.com/akaunting/laravel-money/llms.txt Use the global `money()` helper function to create `Money` objects. It falls back to configuration defaults for currency and conversion if parameters are omitted. ```php // Uses default currency (USD) and default convert (false) from config echo money(500); // "$5.00" // Explicit currency echo money(1000, 'EUR'); // "€10.00" // With conversion from major unit echo money(19.99, 'USD', true); // "$19.99" // In a controller public function show(Order $order) { return view('orders.show', [ 'total' => money($order->amount_cents, $order->currency), ]); } ``` -------------------------------- ### Money Formatting Methods Source: https://context7.com/akaunting/laravel-money/llms.txt Provides various methods for formatting Money objects. `format()` and `formatSimple()` do not require the `intl` PHP extension. `formatForHumans()` and `formatLocale()` require `ext-intl`. ```php use Akaunting\Money\Money; $money = Money::USD(123456); // 123456 cents // Standard format with symbol echo $money->format(); // "$1,234.56" // Plain number only, no symbol echo $money->formatSimple(); // "1,234.56" // Omit decimal places when amount is a whole number echo Money::USD(100000)->formatWithoutZeroes(); // "$1,000" echo Money::USD(100050)->formatWithoutZeroes(); // "$1,000.50" (has cents, keeps decimals) // Human-friendly via ext-intl NumberFormatter (requires ext-intl) echo $money->formatForHumans(); // "$1,234.56" echo $money->formatForHumans('de_DE'); // "$1.234,56" // Custom NumberFormatter callback echo $money->formatForHumans(null, function (\NumberFormatter $fmt) { $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 4); }); // "$1,234.5600" // Locale-aware currency format via ext-intl echo $money->formatLocale('en_US'); // "$1,234.56" echo $money->formatLocale('de_DE'); // "1.234,56 $" // Get underlying numeric value (major unit float) echo $money->getValue(); // 1234.56 // Get raw internal amount (subunit integer/float) echo $money->getAmount(); // 123456 echo $money->getRoundedAmount(); // 123456 ``` -------------------------------- ### Money Comparison Methods Source: https://context7.com/akaunting/laravel-money/llms.txt Compares two Money instances. Ensure both instances share the same currency; otherwise, an InvalidArgumentException is thrown. Includes methods for equality, greater than, less than, and state checks like isZero, isPositive, and isNegative. ```php use Akaunting\Money\Money; $price = Money::USD(1000); $discount = Money::USD(500); $same = Money::USD(1000); $price->compare($discount); // 1 (greater) $discount->compare($price); // -1 (lesser) $price->compare($same); // 0 (equal) $price->equals($same); // true $price->equals($discount); // false $price->greaterThan($discount); // true $price->greaterThanOrEqual($same); // true $price->lessThan($discount); // false $price->lessThanOrEqual($same); // true // State checks Money::USD(0)->isZero(); // true Money::USD(100)->isPositive(); // true Money::USD(-100)->isNegative(); // true // Cross-currency throws InvalidArgumentException try { Money::USD(100)->compare(Money::EUR(100)); } catch (\InvalidArgumentException $e) { echo $e->getMessage(); // 'Different currencies "USD (US Dollar)" and "EUR (Euro)"' } ``` -------------------------------- ### Convert Money Between Currencies Source: https://context7.com/akaunting/laravel-money/llms.txt The `convert()` method converts a `Money` instance to a different currency using a specified exchange rate and optional rounding mode. Demonstrates conversion to EUR, GBP, and JPY with different rates and rounding. ```php use Akaunting\Money\Currency; use Akaunting\Money\Money; $usd = Money::USD(10000); // $100.00 // Convert USD → EUR at rate 0.92 $eur = $usd->convert(Currency::EUR(), 0.92); echo $eur; // "€92.00" // Convert USD → GBP at rate 0.79 $gbp = $usd->convert(Currency::GBP(), 0.79); echo $gbp; // "£79.00" // Convert with custom rounding $jpy = Money::USD(10000)->convert(Currency::JPY(), 149.50, Money::ROUND_HALF_DOWN); echo $jpy; // "¥149500" ``` -------------------------------- ### currency(?string $currency = null) Source: https://context7.com/akaunting/laravel-money/llms.txt Global helper function to create a Currency object. It falls back to the default currency if none is provided. ```APIDOC ## `currency(?string $currency = null)` — Helper Function Global helper that creates a `Currency` object. Falls back to `money.defaults.currency` when `$currency` is `null`. ```php $usd = currency('USD'); echo $usd; // "USD (US Dollar)" echo $usd->getSymbol(); // "$" echo $usd->getPrecision(); // 2 echo $usd->getSubunit(); // 100 echo $usd->getDecimalMark(); // "." echo $usd->getThousandsSeparator(); // "," echo $usd->getPrefix(); // "$" echo $usd->getSuffix(); // "" $eur = currency('EUR'); echo $eur->getPrefix(); // "€" echo $eur->getSuffix(); // "" // Currency with suffix symbol (e.g., SEK) $sek = currency('SEK'); echo $sek->getPrefix(); // "" echo $sek->getSuffix(); // " kr" ``` ``` -------------------------------- ### Helper Function Source: https://context7.com/akaunting/laravel-money/llms.txt A global helper function to create a Money object, falling back to default configuration values when parameters are omitted. ```APIDOC ## money(mixed $amount, ?string $currency = null, ?bool $convert = null) ### Description Global helper that creates a `Money` object. Falls back to `money.defaults.currency` and `money.defaults.convert` from config when parameters are omitted. ### Parameters #### Path Parameters - **$amount** (mixed) - Required - The monetary amount. - **$currency** (string) - Optional - The currency code. - **$convert** (bool) - Optional - Whether to convert the amount from major unit to subunit. ### Request Example ```php // Uses default currency (USD) and default convert (false) from config echo money(500); // "$5.00" // Explicit currency echo money(1000, 'EUR'); // "€10.00" // With conversion from major unit echo money(19.99, 'USD', true); // "$19.99" // In a controller public function show(Order $order) { return view('orders.show', [ 'total' => money($order->amount_cents, $order->currency), ]); } ``` ``` -------------------------------- ### Eloquent Casts for Money and Currency Source: https://context7.com/akaunting/laravel-money/llms.txt Shows how to use `MoneyCast` and `CurrencyCast` to directly cast Eloquent model attributes to `Money` or `Currency` objects. `MoneyCast` stores data as a JSON string, while `CurrencyCast` stores the ISO 4217 string. ```php use Akaunting\Money\Money; use Akaunting\Money\Currency; use Illuminate\Database\Eloquent\Model; class Product extends Model { protected $casts = [ 'price' => Money::class, // uses MoneyCast 'currency' => Currency::class, // uses CurrencyCast ]; } // Writing $product = new Product(); $product->price = Money::USD(2999); // stored as '{"amount":2999,"currency":"USD"}' $product->currency = new Currency('EUR'); // stored as 'EUR' $product->save(); // Reading $product = Product::find(1); echo $product->price; // "$29.99" echo $product->price->getValue(); // 29.99 echo $product->currency; // "EUR (Euro)" // Using in calculations $discounted = $product->price->multiply(0.9); echo $discounted; // "$26.99" ``` -------------------------------- ### Adding Custom Methods with Macros and Mixins Source: https://context7.com/akaunting/laravel-money/llms.txt Extend `Money` and `Currency` classes at runtime using Laravel's Macroable trait. Add instance or static methods with macros, or group multiple methods with mixins. ```php use Akaunting\Money\Currency; use Akaunting\Money\Money; // --- Macro: instance method --- Money::macro('absolute', fn () => $this->isPositive() ? $this : $this->multiply(-1)); $money = Money::USD(1000)->multiply(-1); // -$10.00 echo $money->absolute(); // "$10.00" ``` ```php // --- Macro: static method --- Money::macro('zero', fn (?string $currency = null) => new Money(0, new Currency($currency ?? 'USD'))); echo Money::zero(); // "$0.00" echo Money::zero('EUR'); // "€0.00" ``` ```php // --- Mixin: merge a whole class --- class MoneyHelpers { public function vatAmount(): \Closure { return fn (float $rate = 0.20) => $this->multiply($rate); } public function withVat(): \Closure { return fn (float $rate = 0.20) => $this->multiply(1 + $rate); } } Money::mixin(new MoneyHelpers()); $price = Money::USD(1000); // $10.00 echo $price->vatAmount(); // "$2.00" echo $price->withVat(); // "$12.00" ``` ```php // --- Currency macro --- Currency::macro('isFiat', fn () => !in_array($this->getCurrency(), ['XAU', 'XAG'])); echo Currency::USD()->isFiat() ? 'fiat' : 'commodity'; // "fiat" echo Currency::XAU()->isFiat() ? 'fiat' : 'commodity'; // "commodity" ``` -------------------------------- ### Allocate Monetary Amounts Source: https://context7.com/akaunting/laravel-money/llms.txt The `allocate()` method distributes a monetary amount across multiple parties based on provided ratios. It ensures exact allocation by distributing remainder cents sequentially. ```php use Akaunting\Money\Money; $total = Money::USD(1000); // $10.00 // Split equally three ways [$a, $b, $c] = $total->allocate([1, 1, 1]); echo $a; // "$3.34" (gets the extra cent) echo $b; // "$3.33" echo $c; // "$3.33" // Split by percentage: 70%, 20%, 10% [$majority, $minority, $small] = Money::USD(999)->allocate([70, 20, 10]); echo $majority; // "$7.00" echo $minority; // "$2.00" echo $small; // "$0.99" // Commission split: 60/40 [$merchant, $platform] = Money::USD(5000)->allocate([60, 40]); echo $merchant; // "$30.00" echo $platform; // "$20.00" ``` -------------------------------- ### Money Class Constructor Source: https://context7.com/akaunting/laravel-money/llms.txt Constructs a Money instance. The $amount can be an integer, float, string (including currency-formatted strings), or a callable. When $convert is true the amount is treated as a major unit value (e.g., dollars) and is multiplied by the currency's subunit to produce the stored internal value (e.g., cents). ```APIDOC ## new Money($amount, Currency $currency, bool $convert = false) ### Description Constructs a `Money` instance. The `$amount` can be an integer, float, string (including currency-formatted strings), or a callable. When `$convert` is `true` the amount is treated as a major unit value (e.g., dollars) and is multiplied by the currency's subunit to produce the stored internal value (e.g., cents). ### Parameters #### Path Parameters - **$amount** (int|float|string|callable) - Required - The monetary amount. - **$currency** (Currency) - Required - The currency object. - **$convert** (bool) - Optional - Whether to convert the amount from major unit to subunit. ### Request Example ```php use Akaunting\Money\Currency; use Akaunting\Money\Money; // 500 cents (stored as-is, no conversion) $price = new Money(500, new Currency('USD')); echo $price; // "$5.00" // 5.00 dollars → converted to 500 cents internally $price = new Money(5.00, new Currency('USD'), true); echo $price; // "$5.00" // Parsed from a formatted string $price = new Money('$1,234.56', new Currency('USD')); echo $price->getAmount(); // 123456.0 (stored in cents, float) // Amount from a callable $price = new Money(fn() => 999, new Currency('EUR')); echo $price; // "€9.99" ``` ``` -------------------------------- ### convert(Currency $currency, int|float $ratio, int $roundingMode = ROUND_HALF_UP): Money Source: https://context7.com/akaunting/laravel-money/llms.txt Converts a Money instance to a different currency using a specified exchange rate ratio and optional rounding mode. ```APIDOC ## `convert(Currency $currency, int|float $ratio, int $roundingMode = ROUND_HALF_UP): Money` Converts a `Money` instance to a different currency by applying an exchange rate ratio. ```php use Akaunting\Money\Currency; use Akaunting\Money\Money; $usd = Money::USD(10000); // $100.00 // Convert USD → EUR at rate 0.92 $eur = $usd->convert(Currency::EUR(), 0.92); echo $eur; // "€92.00" // Convert USD → GBP at rate 0.79 $gbp = $usd->convert(Currency::GBP(), 0.79); echo $gbp; // "£79.00" // Convert with custom rounding $jpy = Money::USD(10000)->convert(Currency::JPY(), 149.50, Money::ROUND_HALF_DOWN); echo $jpy; // "¥149500" ``` ``` -------------------------------- ### Currency Management Source: https://context7.com/akaunting/laravel-money/llms.txt Enables overriding the default currency list at runtime, which is useful for testing or multi-tenant applications with custom exchange rates. ```APIDOC ## `Currency::setCurrencies` / `Currency::getCurrencies` Override the full currency list at runtime (useful in tests or multi-tenant apps where each tenant has custom exchange rates). ### Method Signature ```php Currency::getCurrencies(): array Currency::setCurrencies(array $currencies) ``` ### Description - `getCurrencies`: Fetches the currently active list of currencies. - `setCurrencies`: Overrides the global currency list with a custom array of currency definitions. ### Example ```php use Akaunting\Money\Currency; // Fetch the active currency list $currencies = Currency::getCurrencies(); echo count($currencies); // 150+ // Override with a custom subset (e.g., for a closed-loop system) Currency::setCurrencies([ 'USD' => [ 'name' => 'US Dollar', 'code' => 840, 'precision' => 2, 'subunit' => 100, 'symbol' => '$', 'symbol_first' => true, 'decimal_mark' => '.', 'thousands_separator' => ',', 'rate' => 1.0, ], 'EUR' => [ 'name' => 'Euro', 'code' => 978, 'precision' => 2, 'subunit' => 100, 'symbol' => '€', 'symbol_first' => true, 'decimal_mark' => ',', 'thousands_separator' => '.', 'rate' => 0.92, ], ]); $eur = new Currency('EUR'); echo $eur->getRate(); // 0.92 ``` ``` -------------------------------- ### Advanced Money Object Operations Source: https://github.com/akaunting/laravel-money/blob/master/README.md Shows various methods for comparing, converting, and performing arithmetic operations on Money objects. Ensure objects are of the same currency for accurate comparisons and operations. ```php $m1 = Money::USD(500); $m2 = Money::EUR(500); $m1->getCurrency(); $m1->isSameCurrency($m2); $m1->compare($m2); $m1->equals($m2); $m1->greaterThan($m2); $m1->greaterThanOrEqual($m2); $m1->lessThan($m2); $m1->lessThanOrEqual($m2); $m1->convert(Currency::GBP(), 3.5); $m1->add($m2); $m1->subtract($m2); $m1->multiply(2); $m1->divide(2); $m1->allocate([1, 1, 1]); $m1->isZero(); $m1->isPositive(); $m1->isNegative(); $m1->format(); ``` -------------------------------- ### Mutable vs. Immutable Money Objects Source: https://context7.com/akaunting/laravel-money/llms.txt Understand the default immutable nature of `Money` objects, where operations return new instances. Use the `->mutable()` method for in-place mutation in performance-critical loops. ```php use Akaunting\Money\Money; // Immutable (default) $base = Money::USD(1000); $result = $base->add(500); echo $base; // "$10.00" — unchanged echo $result; // "$15.00" — new instance ``` ```php // Mutable $running = Money::USD(0)->mutable(); foreach ([100, 200, 150, 50] as $cents) { $running->add($cents); // mutates in place } echo $running; // "$5.00" (0 + 100 + 200 + 150 + 50 = 500 cents) ``` ```php // Switch back to immutable $snapshot = $running->immutable(); $running->add(9999); // $running changes echo $snapshot; // "$5.00" — unaffected ``` ```php // Check mode $running->isMutable(); // true $snapshot->isImmutable(); // true ``` -------------------------------- ### Currency Class Source: https://context7.com/akaunting/laravel-money/llms.txt The Currency class encapsulates all metadata for an ISO 4217 currency. It supports static calls and direct instantiation. ```APIDOC ## `Currency::USD()` / `new Currency('USD')` — Currency Class The `Currency` class encapsulates all metadata for an ISO 4217 currency. It supports the same static call convention as `Money` for convenient instantiation. ```php use Akaunting\Money\Currency; $usd = Currency::USD(); // same as new Currency('USD') $eur = new Currency('EUR'); echo $usd->getCurrency(); // "USD" echo $usd->getName(); // "US Dollar" echo $usd->getCode(); // 840 echo $usd->getRate(); // 1.0 (default, override in config) echo $usd->isSymbolFirst(); // true echo $usd->render(); // "USD (US Dollar)" echo (string) $usd; // "USD (US Dollar)" // Equality check $usd->equals(Currency::USD()); // true $usd->equals(Currency::EUR()); // false // Serialisation $usd->toArray(); // ['USD' => ['name' => 'US Dollar', 'code' => 840, 'rate' => 1, 'precision' => 2, // 'subunit' => 100, 'symbol' => '$', 'symbol_first' => true, // 'decimal_mark' => '.', 'thousands_separator' => ',', // 'prefix' => '$', 'suffix' => '']] echo $usd->toJson(); // JSON of the above array ``` ``` -------------------------------- ### Defining Custom Money Mixins Source: https://github.com/akaunting/laravel-money/blob/master/README.md Implement mixins to merge methods from another class into the Money or Currency class. This is useful for organizing related custom logic. ```php use Akaunting\Money\Money; class CustomMoney { public function absolute(): Money { return $this->isPositive() ? $this : $this->multiply(-1); } public static function zero(?string $currency = null): Money { return new Money(0, new Currency($currency ?? 'GBP')); } } Money::mixin(new CustomMoney); $money = Money::USD(1000)->multiply(-1); $absolute = $money->absolute(); // Static methods via mixins are supported too: $money = Money::zero(); ``` -------------------------------- ### Override Currency List at Runtime Source: https://context7.com/akaunting/laravel-money/llms.txt Replace the default currency list with a custom subset. This is useful for testing or in multi-tenant applications with unique exchange rates. The `getRate()` method can then be used on a `Currency` instance. ```php use Akaunting\Money\Currency; // Fetch the active currency list $currencies = Currency::getCurrencies(); echo count($currencies); // 150+ // Override with a custom subset (e.g., for a closed-loop system) Currency::setCurrencies([ 'USD' => [ 'name' => 'US Dollar', 'code' => 840, 'precision' => 2, 'subunit' => 100, 'symbol' => '$', 'symbol_first' => true, 'decimal_mark' => '.', 'thousands_separator' => ',', 'rate' => 1.0, ], 'EUR' => [ 'name' => 'Euro', 'code' => 978, 'precision' => 2, 'subunit' => 100, 'symbol' => '€', 'symbol_first' => true, 'decimal_mark' => ',', 'thousands_separator' => '.', 'rate' => 0.92, ], ]); $eur = new Currency('EUR'); echo $eur->getRate(); // 0.92 ``` -------------------------------- ### Perform Arithmetic Operations on Money Objects Source: https://context7.com/akaunting/laravel-money/llms.txt The `Money` class supports immutable arithmetic operations by default, returning new instances. Use the `->mutable()` method for in-place mutation. Supports custom rounding modes for division and multiplication. ```php use Akaunting\Money\Money; $price = Money::USD(1000); // $10.00 $tax = Money::USD(80); // $0.80 $discount = Money::USD(200); // $2.00 // Immutable (default): each call returns a new instance $total = $price->add($tax)->subtract($discount); echo $total; // "$8.80" echo $price; // "$10.00" — unchanged // Mutable: mutates in place $mutablePrice = Money::USD(1000)->mutable(); $mutablePrice->add($tax); echo $mutablePrice; // "$10.80" // Multiply and divide echo Money::USD(1000)->multiply(1.15); // "$11.50" (tax inclusive) echo Money::USD(1000)->divide(4); // "$2.50" echo Money::USD(1000)->divide(3, Money::ROUND_HALF_DOWN); // custom rounding // Add/subtract raw numbers directly echo Money::USD(1000)->add(50); // "$10.50" echo Money::USD(1000)->subtract(25); // "$9.75" ``` -------------------------------- ### Blade Components for Money and Currency Source: https://context7.com/akaunting/laravel-money/llms.txt Utilize and components for a declarative way to display monetary values and currency codes in Blade. Supports attributes for amount, currency, and conversion. ```blade {{-- Amount in cents (no conversion) --}} ``` ```blade {{-- With explicit currency --}} ``` ```blade {{-- With major-unit conversion --}} ``` ```blade {{-- From a model attribute --}} ``` ```blade {{-- Currency component --}} ``` ```blade ``` -------------------------------- ### Defining Static Money Macros Source: https://github.com/akaunting/laravel-money/blob/master/README.md Macros can also be defined for static methods on the Money class, providing utility functions that can be called directly on the class itself. ```php use Akaunting\Money\Currency; use Akaunting\Money\Money; Money::macro('zero', fn (?string $currency = null) => new Money(0, new Currency($currency ?? 'GBP'))); $money = Money::zero(); ``` -------------------------------- ### allocate(array $ratios): array Source: https://context7.com/akaunting/laravel-money/llms.txt Distributes a monetary amount across multiple parties according to given ratios, ensuring accurate allocation without rounding loss. ```APIDOC ## `allocate(array $ratios): array` Distributes a monetary amount across multiple parties according to given ratios, ensuring that every cent is allocated without loss due to rounding (remainder cents are distributed one at a time starting from the first ratio). ```php use Akaunting\Money\Money; $total = Money::USD(1000); // $10.00 // Split equally three ways [$a, $b, $c] = $total->allocate([1, 1, 1]); echo $a; // "$3.34" (gets the extra cent) echo $b; // "$3.33" echo $c; // "$3.33" // Split by percentage: 70%, 20%, 10% [$majority, $minority, $small] = Money::USD(999)->allocate([70, 20, 10]); echo $majority; // "$7.00" echo $minority; // "$2.00" echo $small; // "$0.99" // Commission split: 60/40 [$merchant, $platform] = Money::USD(5000)->allocate([60, 40]); echo $merchant; // "$30.00" echo $platform; // "$20.00" ``` ``` -------------------------------- ### Blade Component for Money and Currency Source: https://github.com/akaunting/laravel-money/blob/master/README.md Use the provided Blade components to render money amounts and currency information in views. The 'convert' attribute enables currency conversion. ```html or or ``` -------------------------------- ### Defining Custom Money Macros Source: https://github.com/akaunting/laravel-money/blob/master/README.md Extend the Money class by defining custom macros. This allows you to add reusable methods directly to the Money object, enhancing its functionality. ```php use Akaunting\Money\Currency; use Akaunting\Money\Money; Money::macro( 'absolute', fn () => $this->isPositive() ? $this : $this->multiply(-1) ); $money = Money::USD(1000)->multiply(-1); $absolute = $money->absolute(); ``` -------------------------------- ### Arithmetic Operations Source: https://context7.com/akaunting/laravel-money/llms.txt Perform arithmetic operations like add, subtract, multiply, and divide on Money objects. Money objects are immutable by default. ```APIDOC ## Arithmetic Operations — `add`, `subtract`, `multiply`, `divide` `Money` is **immutable by default**. Each arithmetic method returns a new `Money` instance. Call `->mutable()` to switch to in-place mutation. All methods accept an optional rounding mode constant (`ROUND_HALF_UP`, `ROUND_HALF_DOWN`, `ROUND_HALF_EVEN`, `ROUND_HALF_ODD`). ```php use Akaunting\Money\Money; $price = Money::USD(1000); // $10.00 $tax = Money::USD(80); // $0.80 $discount = Money::USD(200); // $2.00 // Immutable (default): each call returns a new instance $total = $price->add($tax)->subtract($discount); echo $total; // "$8.80" echo $price; // "$10.00" — unchanged // Mutable: mutates in place $mutablePrice = Money::USD(1000)->mutable(); $mutablePrice->add($tax); echo $mutablePrice; // "$10.80" // Multiply and divide echo Money::USD(1000)->multiply(1.15); // "$11.50" (tax inclusive) echo Money::USD(1000)->divide(4); // "$2.50" echo Money::USD(1000)->divide(3, Money::ROUND_HALF_DOWN); // custom rounding // Add/subtract raw numbers directly echo Money::USD(1000)->add(50); // "$10.50" echo Money::USD(1000)->subtract(25); // "$9.75" ``` ``` -------------------------------- ### Currency Validation Rule Source: https://context7.com/akaunting/laravel-money/llms.txt Use the `CurrencyRule` or the `currency_code` string rule to validate that an input value is a valid ISO 4217 currency code. This ensures data integrity for currency fields. ```php use Akaunting\Money\Rules\CurrencyRule; use Illuminate\Support\Facades\Validator; // As a rule object $validator = Validator::make( ['currency' => 'USD'], ['currency' => ['required', 'string', new CurrencyRule()]] ); $validator->passes(); // true $validator = Validator::make( ['currency' => 'FAKE'], ['currency' => new CurrencyRule()] ); $validator->fails(); // true $validator->errors()->first('currency'); // "The currency is invalid." ``` ```php // As a string rule (registered by the service provider) $request->validate([ 'currency' => 'required|string|currency_code', ]); ``` ```php // In a form request class UpdateSettingsRequest extends FormRequest { public function rules(): array { return [ 'default_currency' => ['required', 'string', new CurrencyRule()], 'amount' => ['required', 'numeric', 'min:0'], ]; } } ``` -------------------------------- ### Blade Directives for Money and Currency Source: https://context7.com/akaunting/laravel-money/llms.txt Use @money and @currency directives to render monetary values and currency codes directly in Blade templates. Specify currency codes and conversion options as needed. ```blade {{-- Basic usage --}} @money(500) {{-- $5.00 (uses default currency from config) --}} @money(500, 'USD') {{-- $5.00 --}} @money(500, 'EUR') {{-- €5.00 --}} @money(500, 'USD', true) {{-- $500.00 (convert from major unit) --}} ``` ```blade {{-- Currency display --}} @currency('USD') {{-- USD (US Dollar) --}} @currency('GBP') {{-- GBP (Pound Sterling) --}} ``` ```blade {{-- With a variable --}} @money($product->amount_cents, $product->currency_code) ``` -------------------------------- ### Blade Directives for Money and Currency Source: https://github.com/akaunting/laravel-money/blob/master/README.md Utilize Blade directives to easily display formatted money values or currency codes directly within your Blade views. These directives abstract away the PHP instantiation. ```blade @money(500) @money(500, 'USD') @currency('USD') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.