### MoneyCast set() Method Example Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Demonstrates how the set method handles different input types for the amount, including strings with currency, integers, floats, and Money instances. It shows the normalization to minor units for storage. ```php $invoice = new Invoice(); $invoice->amount = '100.50 USD'; // String with currency $invoice->currency = 'USD'; // set() converts '100.50' to 10050 (minor units) and stores currency as 'USD' $invoice->amount = 100; // Integer $invoice->tax = 10.5; // Float $invoice->discount = Money::of(5, 'EUR'); // Money instance // All are normalized to their respective integer minor unit representations ``` -------------------------------- ### Install Laravel Money Package Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/README.md Install the package using Composer. This command adds the package as a dependency to your Laravel project. ```bash composer require elegantly/laravel-money ``` -------------------------------- ### Example: Rounding Mode with MoneyParser Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md Demonstrates how changing the 'rounding_mode' configuration affects the output of MoneyParser when parsing a value with high precision. The default is RoundingMode::HalfUp. ```php use Elegantly\Money\MoneyParser; use Brick\Math\RoundingMode; // With RoundingMode::HalfUp (default) MoneyParser::parse(99.995, 'EUR'); // €100.00 // With RoundingMode::Down config(['money.rounding_mode' => RoundingMode::Down]); MoneyParser::parse(99.995, 'EUR'); // €99.99 ``` -------------------------------- ### MoneyCast Constructor and Usage Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Demonstrates how to use the MoneyCast class in Eloquent models for handling monetary values. It covers dynamic currency, fixed currency, and default currency configurations, along with examples of creating and accessing model instances. ```APIDOC ## MoneyCast Constructor and Usage ### Description This section details the usage of the `MoneyCast` class as an Eloquent attribute cast. It explains how to configure it for dynamic currency (read from a model attribute), fixed currency (hardcoded), or the default configured currency. Examples show how to define casts in a model and how to create and interact with model instances that use `MoneyCast`. ### Constructor Signature ```php public function __construct(protected ?string $currencyOrAttribute = null) ``` ### Parameters #### Constructor Parameters - **currencyOrAttribute** (`?string`) - Optional - Either an ISO 4217 currency code (e.g., 'USD', 'EUR') or a model attribute name that contains the currency code. If null, uses the configured default currency. ### Example Usage: ```php use Elegantly\Money\MoneyCast; use Illuminate\Database\Eloquent\Model; use Brick\Money\Money; class Invoice extends Model { protected function casts(): array { return [ // Dynamic currency: reads currency from the 'currency' attribute 'amount' => MoneyCast::of('currency'), // Fixed currency: always uses EUR 'tax' => MoneyCast::of('EUR'), // Default currency: uses config('money.default_currency') 'discount' => MoneyCast::class, ]; } } $invoice = Invoice::create([ 'amount' => 100, // Stored as integer minor units (cents) 'currency' => 'USD', 'tax' => 10.50, // Automatically converted to minor units 'discount' => '5.00' // Parsed from string ]); echo $invoice->amount->getAmount()->toFloat(); // 100.0 echo $invoice->amount->getCurrency()->getCode(); // USD echo $invoice->tax->getAmount()->toFloat(); // 10.50 ``` ``` -------------------------------- ### MoneyCast get() Method Signature Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Defines the signature for the get method, which casts database values to Money instances. It handles raw values from the database and returns a Money object or null. ```php public function get( Model $model, string $key, mixed $value, array $attributes ): ?Money ``` -------------------------------- ### get() Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Casts the database value into a Money instance. It handles conversion from minor units to a Money object, considering currency configuration. ```APIDOC ## get() ### Description Casts the value from the database into a Money instance. ### Method `get` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **model** (`Model`) - Required - The Eloquent model instance - **key** (`string`) - Required - The attribute name being cast - **value** (`mixed`) - Required - The raw value from the database (integer minor units or null) - **attributes** (`array`) - Required - All attributes from the model instance ### Returns `?Money` - A Money instance or null if the value is null. ### Throws - Throws an exception if the currency is invalid. ### Details - Converts the integer minor unit amount to a Money instance using `Money::ofMinor()`. - Currency is determined by: (1) the model attribute if configured, (2) the fixed currency code if set, or (3) the default currency from config. - Returns null if the database value is null. ``` -------------------------------- ### MoneyCast::set() Return Example Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/types.md Demonstrates the expected output format of the `set()` method when processing input attributes. The returned array maps column names to their corresponding values, which are integers for amounts, strings for currency codes, or null. ```php // Input attributes ['currency' => 'EUR', 'price' => null, ...] // set() returns [ 'price' => 10050, // int: 100.50 EUR in minor units 'currency' => 'EUR' // string: currency code ] ``` -------------------------------- ### MoneyCast serialize() Method Example Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Illustrates the output of the serialize method when an Eloquent model is converted to an array, typically for API responses. It shows the amount as a float in major units. ```php $invoice = Invoice::find(1); // When serialized to JSON (e.g., in API responses): $invoice->toArray(); // ['amount' => 100.50, 'currency' => 'USD', ...] ``` -------------------------------- ### Configure MoneyCast with Currency Attribute Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md When a currency attribute is configured, it is updated when the amount is set. This example shows how to configure the casts method in a model to use MoneyCast with a specific currency attribute. ```php protected function casts(): array { return [ 'amount' => MoneyCast::of('currency'), ]; } $invoice = new Invoice(); $invoice->amount = '99.99 EUR'; // Sets both 'amount' => 9999 and 'currency' => 'EUR' ``` -------------------------------- ### Database Migration for Money Storage Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/README.md Example migration schema for storing monetary values. It uses a bigInteger for the amount (in smallest currency unit) and a string for the currency code to ensure precision. ```php Schema::create('invoices', function (Blueprint $table) { $table->id(); $table->bigInteger('amount'); // e.g., 1000 = $10.00 $table->string('currency', 3); // ISO 4217 code $table->timestamps(); }); ``` -------------------------------- ### PHP MoneyParser parseString Examples Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyParser.md Illustrates the internal usage of the parseString method. It shows how the method handles currency precedence when a currency code is present in the input string versus when it relies on the provided currency parameter. ```php // Internal usage (normally called by parse()) $money = MoneyParser::parseString('EUR 100.50', 'USD'); // Returns Money(€100.50, EUR) — string currency takes precedence $money = MoneyParser::parseString('100.50', 'USD'); // Returns Money($100.50, USD) — uses parameter currency ``` -------------------------------- ### Eloquent Model Integration with MoneyCast Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Integrate MoneyCast into your Eloquent models to handle monetary values. This example demonstrates configuring casts for a separate currency column, a fixed currency, and using the default currency from configuration. ```php use Elegantly\Money\MoneyCast; use Brick\Money\Money; class Order extends Model { protected function casts(): array { return [ // Currency stored in a separate column 'total' => MoneyCast::of('currency'), // Fixed currency (e.g., always in USD) 'processing_fee' => MoneyCast::of('USD'), // Default currency from config 'discount' => MoneyCast::class, ]; } } // Create an order $order = Order::create([ 'total' => '250.75', 'currency' => 'EUR', 'processing_fee' => 2.99, 'discount' => 10, ]); // Access as Money objects $order->total; // Money instance in EUR $order->total->getAmount()->toFloat(); // 250.75 // Modify and save $order->total = Money::of(300, 'EUR'); $order->save(); // JSON serialization uses floats echo json_encode($order); // {"id": 1, "total": 300.75, "currency": "EUR", "processing_fee": 2.99, ...} ``` -------------------------------- ### Using MoneyCast::of() in Eloquent Model Casts Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Example demonstrating how to use the MoneyCast::of() method within the casts() method of an Eloquent model to define custom casts for price and cost attributes. ```php protected function casts(): array { return [ 'price' => MoneyCast::of('currency'), 'cost' => MoneyCast::of('EUR'), ]; } ``` -------------------------------- ### Validating Money Input in Livewire Components Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Use the `#[Validate]` attribute with `ValidMoney` to enforce monetary validation rules within Livewire components. This example shows how to set nullable, min, and max constraints. ```php namespace App\Livewire; use Elegantly\Money\Rules\ValidMoney; use Livewire\Component; class PriceInput extends Component { #[Validate([ new ValidMoney(nullable: false, min: 0, max: 1000) ])] public ?string $price = null; public function save() { $this->validate(); // Price is valid } public function render() { return view('livewire.price-input'); } } ``` -------------------------------- ### Direct Usage of Money Classes Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyServiceProvider.md Demonstrates direct instantiation of MoneyCast, MoneyParser, and ValidMoney classes without requiring service container bindings. Ensure necessary imports are present. ```php use Elegantly\Money\MoneyCast; use Elegantly\Money\MoneyParser; use Elegantly\Money\Rules\ValidMoney; // Use directly new MoneyCast('EUR'); MoneyParser::parse(100, 'EUR'); new ValidMoney(nullable: false); ``` -------------------------------- ### Run Test Suite Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/README.md Execute the project's test suite using Composer. ```bash composer test ``` -------------------------------- ### Configuration Validation at Startup Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/errors.md Verify critical money package configurations, such as the default currency and rounding mode, during application startup. This prevents runtime errors caused by misconfigurations. ```php // In a service provider or middleware use Brick\Money\Currency; use Brick\Math\RoundingMode; try { // Validate default currency Currency::of(config('money.default_currency')); // Validate rounding mode $mode = config('money.rounding_mode'); if (!$mode instanceof RoundingMode) { throw new InvalidArgumentException('Invalid rounding mode configuration'); } } catch (Exception $e) { throw new RuntimeException('Invalid money configuration: ' . $e->getMessage()); } ``` -------------------------------- ### Publish Configuration File Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/README.md Publish the configuration file to customize default settings. This makes the configuration file available for modification. ```bash php artisan vendor:publish --tag="money-config" ``` -------------------------------- ### ValidMoney Rule in Livewire Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/README.md Implement the ValidMoney validation rule within Livewire components to validate monetary input. This example enforces non-nullability and a range between 0 and 100. ```php namespace App\Livewire; use Elegantly\Money\Rules\ValidMoney; use Livewire\Component; class CustomComponent extends Component { #[Validate([ new ValidMoney(nullable: false, min: 0, max: 100), ])] public ?int $price = null; } ``` -------------------------------- ### Package Configuration with Fluent Builder Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyServiceProvider.md This PHP snippet demonstrates the fluent builder pattern used within the configurePackage method to set up the Laravel Money package. It enables translation and configuration file publishing. ```php $package ->name('laravel-money') // Set package name ->hasTranslations() // Enable translation publishing ->hasConfigFile(); // Enable config publishing ``` -------------------------------- ### MoneyCast Constructor and Usage Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Demonstrates how to use MoneyCast in Eloquent model casts for dynamic currency, fixed currency, and default currency scenarios. Shows how to create a model with monetary values and access them as Money objects. ```php use Elegantly\Money\MoneyCast; use Illuminate\Database\Eloquent\Model; use Brick\Money\Money; class Invoice extends Model { protected function casts(): array { return [ // Dynamic currency: reads currency from the 'currency' attribute 'amount' => MoneyCast::of('currency'), // Fixed currency: always uses EUR 'tax' => MoneyCast::of('EUR'), // Default currency: uses config('money.default_currency') 'discount' => MoneyCast::class, ]; } } $invoice = Invoice::create([ 'amount' => 100, 'currency' => 'USD', 'tax' => 10.50, 'discount' => '5.00' ]); echo $invoice->amount->getAmount()->toFloat(); // 100.0 echo $invoice->amount->getCurrency()->getCode(); // USD echo $invoice->tax->getAmount()->toFloat(); // 10.50 ``` -------------------------------- ### ValidMoney Rule in Form Requests Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/README.md Apply the ValidMoney validation rule in Form Requests to validate monetary input. This example demonstrates setting nullable, min, and max constraints for the 'price' field. ```php namespace App\Http\Requests; use Elegantly\Money\Rules\ValidMoney; use Illuminate\Foundation\Http\FormRequest; class CustomFormRequest extends FormRequest { public function rules() { return [ 'price' => [ new ValidMoney( nullable: false, min: 0, max: 100 ), ], ]; } } ``` -------------------------------- ### Read and Override Configuration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md Demonstrates how to read the current default currency and rounding mode, and how to temporarily override the default currency for subsequent operations. Changes are effective until reset or the application restarts. ```php use Brick\Math\RoundingMode; // Read current configuration $currency = config('money.default_currency'); // 'USD' $rounding = config('money.rounding_mode'); // RoundingMode::HalfUp // Temporarily override configuration config(['money.default_currency' => 'EUR']); // This is now used by all subsequent calls $parsed = MoneyParser::parse('100', null); // Uses EUR // Reset to original config(['money.default_currency' => 'USD']); ``` -------------------------------- ### Environment-Aware Configuration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md Allows default currency and rounding mode to be set via environment variables. ```php // config/money.php use Brick\Math\RoundingMode; return [ 'default_currency' => env('MONEY_DEFAULT_CURRENCY', 'USD'), 'rounding_mode' => env('MONEY_ROUNDING_MODE') === 'floor' ? RoundingMode::Floor : RoundingMode::HalfUp, ]; ``` -------------------------------- ### Store Money in Eloquent Models Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/README.md Demonstrates how to use MoneyCast to store monetary values in Eloquent models, supporting dynamic currency. ```php use Elegantly\Money\MoneyCast; class Invoice extends Model { protected function casts(): array { return [ 'amount' => MoneyCast::of('currency'), // Dynamic currency ]; } } $invoice = Invoice::create([ 'amount' => '1,234.50 USD', 'currency' => 'USD', ]); echo $invoice->amount->getAmount()->toFloat(); // 1234.50 ``` -------------------------------- ### Publishing Money Package Configuration and Translations Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/README.md Commands to manually publish the package's configuration file and translation files to your Laravel project. Use these if automatic publication fails or is disabled. ```bash php artisan vendor:publish --tag="money-config" ``` ```bash php artisan vendor:publish --tag="money-translations" ``` -------------------------------- ### ValidMoney Rule in Livewire Components Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/errors.md Illustrates the usage of the ValidMoney validation rule within Livewire components, leveraging PHP 8 attributes for concise validation setup. This is suitable for real-time validation in Livewire applications. ```php #[Validate([ new ValidMoney(nullable: false), ])] public ?string $price = null; // $this->getErrorBag()->first('price') contains the message if validation fails ``` -------------------------------- ### Default Configuration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/README.md Sets the default currency and rounding mode for monetary operations. Ensure Brick\Math\RoundingMode is imported. ```php use Brick\Math\RoundingMode; return [ 'default_currency' => 'USD', 'rounding_mode' => RoundingMode::HalfUp, ]; ``` -------------------------------- ### MoneyCast Constructor Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/types.md The MoneyCast constructor accepts a single parameter for currency configuration. ```APIDOC ## MoneyCast Constructor ### Description Initializes MoneyCast with currency information. ### Method __construct ### Parameters #### Path Parameters - **currencyOrAttribute** (string | null) - Required - Accepts null for default currency, a 3-character string for a fixed currency code, or a string matching a model attribute name for dynamic currency. ``` -------------------------------- ### set() Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Prepares the Money value for storage in the database, converting it to integer minor units. ```APIDOC ## set() ### Description Prepare the value for storage in the database. ### Method `set` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **model** (`Model`) - Required - The Eloquent model instance - **key** (`string`) - Required - The attribute name being cast - **value** (`mixed`) - Required - The value to store (Money, int, float, string, or null) - **attributes** (`array`) - Required - All attributes from the model instance ### Returns `array` - An associative array of database column names to values ready for storage. ### Details - Accepts: `Money` instances, integers, floats, strings, or null. - Uses `MoneyParser` to convert strings to Money objects. - Returns the amount as an integer in minor units (e.g., 1000 for $10.00). - If a currency attribute is configured, also returns the currency code. - Strings are parsed with the pattern `[A-Z]{3}? ?[-\d,.]*` to extract optional currency codes. ### Example ```php $invoice = new Invoice(); $invoice->amount = '100.50 USD'; // String with currency $invoice->currency = 'USD'; // set() converts '100.50' to 10050 (minor units) and stores currency as 'USD' $invoice->amount = 100; // Integer $invoice->tax = 10.5; // Float $invoice->discount = Money::of(5, 'EUR'); // Money instance // All are normalized to their respective integer minor unit representations ``` ``` -------------------------------- ### Instantiate ValidMoney Rule (Using String Representations for Boundaries) Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Creates a new ValidMoney rule instance using string representations for the minimum and maximum boundaries. The rule will parse these strings into comparable monetary values. ```php use Elegantly\Money\Rules\ValidMoney; // Using string representations new ValidMoney( min: '10.50', max: '999.99' ); ``` -------------------------------- ### Default Configuration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyParser.md Shows the default configuration file for the money parser, including the default currency and rounding mode. ```php // config/money.php return [ 'default_currency' => 'USD', 'rounding_mode' => RoundingMode::HalfUp, ]; ``` -------------------------------- ### Instantiate ValidMoney Rule (With Minimum Boundary) Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Creates a new ValidMoney rule instance with a minimum boundary. Values must be greater than or equal to the specified minimum. ```php use Elegantly\Money\Rules\ValidMoney; // With min boundary (0 to any amount) new ValidMoney(min: 0); ``` -------------------------------- ### Instantiate ValidMoney Rule (Using Money Instances for Boundaries) Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Creates a new ValidMoney rule instance using Money objects for the minimum and maximum boundaries. This ensures precise currency-aware comparisons. ```php use Elegantly\Money\Rules\ValidMoney; use Illuminate\Support\Number; // Assuming Money class is available use Money\Money; // Assuming Money class is available // Using Money instances for boundaries new ValidMoney( min: Money::of(10, 'USD'), max: Money::of(1000, 'USD') ); ``` -------------------------------- ### Instantiate ValidMoney Rule (With Min and Max Boundaries) Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Creates a new ValidMoney rule instance with both minimum and maximum boundaries. Values must fall within the specified range. ```php use Elegantly\Money\Rules\ValidMoney; // With both min and max (10 to 100) new ValidMoney(min: 10, max: 100); ``` -------------------------------- ### MoneyCast set() Method Signature Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md Defines the signature for the set method, which prepares Money values for database storage. It accepts various input types and returns an array ready for database insertion. ```php public function set( Model $model, string $key, mixed $value, array $attributes ): array ``` -------------------------------- ### Euro-Centric Application Configuration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md Sets the default currency to EUR and rounding mode to HalfUp. ```php // config/money.php use Brick\Math\RoundingMode; return [ 'default_currency' => 'EUR', 'rounding_mode' => RoundingMode::HalfUp, ]; ``` -------------------------------- ### USD-Centric Application Configuration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md Sets the default currency to USD and rounding mode to HalfUp. ```php // config/money.php use Brick\Math\RoundingMode; return [ 'default_currency' => 'USD', 'rounding_mode' => RoundingMode::HalfUp, ]; ``` -------------------------------- ### ValidMoney Rule with Various Input Formats Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Demonstrates the flexibility of the `ValidMoney` rule by testing it with different input formats, including integers, floats, strings with and without currency, formatted strings, and Money instances. Ensure inputs are within the specified min/max bounds. ```php use Elegantly\Money\Rules\ValidMoney; $rule = new ValidMoney(nullable: false, min: 0, max: 1000); // All of these pass validation if within bounds: $rule->validate('price', null, fn() => null); // Depends on nullable setting $rule->validate('price', '', fn() => null); // Depends on nullable setting $rule->validate('price', 100, fn() => null); // Integer (major units) $rule->validate('price', 100.50, fn() => null); // Float $rule->validate('price', '100', fn() => null); // String without currency $rule->validate('price', 'USD 100.50', fn() => null); // String with currency $rule->validate('price', '1,234.56', fn() => null); // Formatted string $rule->validate('price', Money::of(100, 'USD'), fn() => null); // Money instance ``` -------------------------------- ### MoneyCast Configuration Usage Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md The MoneyCast class utilizes configuration for default currency and parsing. ```php class MoneyCast implements CastsAttributes { public function get(Model $model, string $key, mixed $value, array $attributes): ?Money { $default = config('money.default_currency'); // Uses default_currency // ... } public function set(Model $model, string $key, mixed $value, array $attributes): array { // Uses MoneyParser which reads rounding_mode $money = MoneyParser::parse($value, $this->getCurrency($attributes)); // ... } } ``` -------------------------------- ### Instantiate ValidMoney Rule (With Maximum Boundary) Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Creates a new ValidMoney rule instance with a maximum boundary. Values must be less than or equal to the specified maximum. ```php use Elegantly\Money\Rules\ValidMoney; // With max boundary (0 to 100) new ValidMoney(max: 100); ``` -------------------------------- ### Supported Input Formats for MoneyParser and MoneyCast Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/README.md Demonstrates various data types accepted by MoneyParser and MoneyCast, including null, integers, floats, strings, and Money instances. Shows how currency codes in strings can override the default currency. ```php null // Returns null '' // Returns null ' ' // Returns null ``` ```php 100 // €100.00 -50 // -€50.00 ``` ```php 100.50 // €100.50 1234.56 // €1,234.56 ``` ```php '100' // €100.00 '100.50' // €100.50 '1,234.56' // €1,234.56 '1 234.56' // €1,234.56 ``` ```php 'EUR 100' // €100.00 (EUR overrides) 'USD 1,234.56' // $1,234.56 (USD overrides) 'GBP -50.25' // -£50.25 (GBP overrides) ``` ```php Money::of(100, 'EUR') // Returned as-is ``` -------------------------------- ### ValidMoney Constructor Signature Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/types.md Shows the constructor for ValidMoney, which accepts parameters for nullability, minimum, and maximum boundaries. ```php public function __construct( public bool $nullable = true, public AbstractMoney|BigNumber|int|string|null $min = null, public AbstractMoney|BigNumber|int|string|null $max = null ) ``` -------------------------------- ### Instantiate ValidMoney Rule (Using BigNumber for Boundaries) Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Creates a new ValidMoney rule instance using BigNumber objects for the minimum and maximum boundaries. This is useful for high-precision monetary values. ```php use Elegantly\Money\Rules\ValidMoney; use Illuminate\Support\Number; // Assuming BigNumber class is available use Brick\Math\BigNumber; // Assuming BigNumber class is available // Using BigNumber for boundaries new ValidMoney( min: BigNumber::of('10.50'), max: BigNumber::of('999.99') ); ``` -------------------------------- ### Money Package Configuration File Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyServiceProvider.md This is the default configuration file for the money package. It defines the default currency and rounding mode. Access these settings using the `config()` helper function. ```php 'USD', 'rounding_mode' => RoundingMode::HalfUp, ]; ``` ```php // Access configuration $currency = config('money.default_currency'); $roundingMode = config('money.rounding_mode'); ``` -------------------------------- ### Default Configuration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/README.md The default configuration file sets the default currency for the application. This can be overridden in the published configuration file. ```php return [ 'default_currency' => 'USD', ]; ``` -------------------------------- ### MoneyCast Constructor Signature Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/types.md Defines the constructor for MoneyCast, accepting an optional currency or attribute string to set the currency. ```php public function __construct( protected ?string $currencyOrAttribute = null ) ``` -------------------------------- ### Instantiate ValidMoney Rule (Require Non-Null) Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Creates a new ValidMoney rule instance that requires non-null values. Null or empty values will fail validation. ```php use Elegantly\Money\Rules\ValidMoney; // Require non-null values new ValidMoney(nullable: false); ``` -------------------------------- ### Parse Empty String Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyParser.md Demonstrates parsing an empty string, which results in null. ```php // Empty string MoneyParser::parse('', 'EUR'); // null ``` -------------------------------- ### Eloquent Model Integration with MoneyCast Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyServiceProvider.md Shows how to integrate MoneyCast into an Eloquent model's casts array to handle monetary values. This allows for seamless casting of attributes to Money objects. ```php use Elegantly\Money\MoneyCast; use Illuminate\Database\Eloquent\Model; class Invoice extends Model { protected function casts(): array { return [ 'amount' => MoneyCast::of('currency'), ]; } } ``` -------------------------------- ### MoneyCast::get() and ::set() Method Signatures Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/types.md These are the method signatures for `MoneyCast::get()` and `MoneyCast::set()`, illustrating their parameter and return types. The `$attributes` parameter represents the model's attribute bag. ```php public function get( Model $model, string $key, mixed $value, array $attributes // array ): ?Money public function set( Model $model, string $key, mixed $value, array $attributes // array ): array ``` -------------------------------- ### Handle API Input with MoneyParser Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyParser.md Parse monetary values from API requests using MoneyParser, allowing for dynamic currency specification. Includes error handling for invalid inputs. ```php use Elegantly\Money\MoneyParser; class OrderController { public function store(Request $request) { $totalAmount = MoneyParser::parse( $request->input('total_amount'), $request->input('currency', 'USD') ); if ($totalAmount === null) { return response()->json(['error' => 'Invalid amount'], 422); } // Process the order with the parsed Money object } } ``` -------------------------------- ### ValidMoney Constructor Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Instantiates the ValidMoney validation rule. It allows configuration for nullability and optional minimum and maximum monetary boundaries. ```APIDOC ## Constructor ValidMoney ### Description Instantiates the `ValidMoney` validation rule, allowing configuration for nullability and optional minimum and maximum monetary boundaries. ### Method `__construct` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **nullable** (`bool`) - Optional - Default: `true` - If true, null and empty values pass validation. If false, null values fail validation. * **min** (`AbstractMoney|BigNumber|int|string|null`) - Optional - Default: `null` - Minimum allowed value (inclusive). Can be a Money instance, BigNumber, int, string, or null for no minimum. * **max** (`AbstractMoney|BigNumber|int|string|null`) - Optional - Default: `null` - Maximum allowed value (inclusive). Can be a Money instance, BigNumber, int, string, or null for no maximum. ### Request Example ```php use Elegantly\Money\Rules\ValidMoney; // Allow null values new ValidMoney(); // Require non-null values new ValidMoney(nullable: false); // With min boundary (0 to any amount) new ValidMoney(min: 0); // With max boundary (0 to 100) new ValidMoney(max: 100); // With both min and max (10 to 100) new ValidMoney(min: 10, max: 100); // Using Money instances for boundaries new ValidMoney( min: Money::of(10, 'USD'), max: Money::of(1000, 'USD') ); // Using BigNumber for boundaries new ValidMoney( min: BigNumber::of('10.50'), max: BigNumber::of('999.99') ); // Using string representations new ValidMoney( min: '10.50', max: '999.99' ); ``` ### Response This method does not return a value directly; it initializes the rule object. #### Success Response N/A #### Response Example N/A ### Error Handling - If `nullable` is false, null and empty strings will fail validation with a 'not valid money' error. - Min/max bounds are inclusive and compared against the parsed monetary value. ``` -------------------------------- ### Configuring Minimum Boundary Types for ValidMoney Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/errors.md Shows the flexibility of the ValidMoney rule's 'min' parameter, accepting various numeric types including integers, floats, numeric strings, BigNumber objects, and Money instances. This allows for precise control over minimum value constraints. ```php new ValidMoney(min: 0.01); // Integer or float new ValidMoney(min: '0.01'); // Numeric string new ValidMoney(min: BigNumber::of('0.01')); // BigNumber new ValidMoney(min: Money::of('0.01', 'USD')); // Money instance ``` -------------------------------- ### Import Monetary Data from External Systems Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyParser.md Parse diverse monetary data formats from external sources like APIs or files into Money objects using MoneyParser. Handles various input types and specifies a default currency. ```php use Elegantly\Money\MoneyParser; // Converting data from an external API or file $prices = [ 'price_1' => 'EUR 100.50', 'price_2' => 1234, 'price_3' => 99.99, 'price_4' => '50', ]; foreach ($prices as $key => $value) { $money = MoneyParser::parse($value, 'EUR'); if ($money) { $product->$key = $money; } } ``` -------------------------------- ### Handling MoneyException for Mismatched Currencies Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/errors.md Illustrates how a MoneyException is thrown when attempting to perform operations between Money instances with different currencies. This typically occurs in the underlying Brick\Money library. ```php use Brick\Money\Money; $usd = Money::of(100, 'USD'); $eur = Money::of(100, 'EUR'); $usd->plus($eur); // Throws MoneyException: Cannot perform operation with different currencies ``` -------------------------------- ### Instantiate ValidMoney Rule (Allow Null) Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Creates a new ValidMoney rule instance that allows null or empty values to pass validation. This is the default behavior. ```php use Elegantly\Money\Rules\ValidMoney; // Allow null values new ValidMoney(); ``` -------------------------------- ### Eloquent Model with MoneyCast Type Hint Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/types.md Define a MoneyCast for the 'amount' property in your Eloquent model to enable type hinting. This allows IDEs to recognize the property as a \"Money\" object, providing autocompletion and type checking. ```php use Brick\Money\Money; use Elegantly\Money\MoneyCast; /** * @property Money $amount * @property string $currency */ class Invoice extends Model { protected function casts(): array { return [ 'amount' => MoneyCast::of('currency'), ]; } } // IDE autocomplete and type checking recognize $invoice->amount as Money $invoice = Invoice::find(1); $amount = $invoice->amount; // Type: Money $float = $amount->getAmount()->toFloat(); // Type: float ``` -------------------------------- ### ValidMoney Constructor Parameters Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Defines the parameters for the ValidMoney constructor, including nullable, min, and max boundaries. These parameters control how monetary values are validated. ```php public function __construct( public bool $nullable = true, public AbstractMoney|BigNumber|int|string|null $min = null, public AbstractMoney|BigNumber|int|string|null $max = null ): void ``` -------------------------------- ### Parsing Integers Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyParser.md Illustrates parsing integer values into Money objects. The integer is converted to the specified currency. ```php MoneyParser::parse(100, 'EUR'); // €100.00 MoneyParser::parse(-50, 'USD'); // -$50.00 MoneyParser::parse(0, 'GBP'); // £0.00 ``` -------------------------------- ### Currency Precedence in Parsing Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyParser.md Demonstrates how currency codes within the input string take precedence over the provided currency parameter. Use this to ensure the correct currency is parsed when the input string is explicit. ```php // Parameter currency is ignored if string has currency code MoneyParser::parse('EUR 100', 'USD'); // Returns EUR, not USD MoneyParser::parse('GBP 50.25', 'EUR'); // Returns GBP, not EUR MoneyParser::parse('100', 'USD'); // Returns USD (no code in string) ``` -------------------------------- ### Environment-Specific Configuration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md Customize configuration per environment using Laravel's .env file. Modify the config/money.php file to bind configuration values to environment variables. ```php env('MONEY_DEFAULT_CURRENCY', 'USD'), 'rounding_mode' => match (env('MONEY_ROUNDING_MODE', 'HalfUp')) { 'HalfDown' => RoundingMode::HalfDown, 'HalfEven' => RoundingMode::HalfEven, 'Up' => RoundingMode::Up, 'Down' => RoundingMode::Down, 'Ceiling' => RoundingMode::Ceiling, 'Floor' => RoundingMode::Floor, default => RoundingMode::HalfUp, }, ]; ``` ```env MONEY_DEFAULT_CURRENCY=EUR MONEY_ROUNDING_MODE=HalfEven ``` -------------------------------- ### Parse Monetary Values Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/README.md Shows various ways to parse monetary values using MoneyParser, handling different input types and currency overrides. ```php use Elegantly\Money\MoneyParser; $money = MoneyParser::parse('100.50', 'EUR'); $money = MoneyParser::parse(100, 'USD'); $money = MoneyParser::parse('USD 100.50', 'EUR'); // Currency code overrides $money = MoneyParser::parse('', 'EUR'); // null (graceful) ``` -------------------------------- ### Multi-Currency with Conservative Rounding Configuration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md Configures the default currency as USD and uses a conservative rounding mode (Down). ```php // config/money.php use Brick\Math\RoundingMode; return [ 'default_currency' => 'USD', 'rounding_mode' => RoundingMode::Down, // Always round down for conservative calculations ]; ``` -------------------------------- ### Default Configuration File Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md This is the default configuration file for the Laravel Money package. It sets the default currency and rounding mode. ```php 'USD', /** * Rounding mode used when parsing money */ 'rounding_mode' => RoundingMode::HalfUp, ]; ``` -------------------------------- ### Validating Minimum Money Value Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/errors.md Demonstrates how to use the ValidMoney rule with a minimum boundary to ensure monetary values meet a specific threshold. This is useful for enforcing minimum purchase amounts or pricing tiers. ```php new ValidMoney(min: 10) // Fails for values less than 10: Validator::make(['price' => '5'], ['price' => new ValidMoney(min: 10)])->fails(); // Error: "The value must be greater than 10" // Passes for values >= 10: Validator::make(['price' => '10'], ['price' => new ValidMoney(min: 10)])->passes(); ``` -------------------------------- ### MoneyCast Input Formats Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md The set() method of MoneyCast accepts various input formats for monetary values, including integers, floats, strings with or without currency, and Money instances. It also handles null values. ```php // Integer (major units) $model->amount = 100; // Treated as $100.00 // Float (major units) $model->amount = 100.50; // String without currency $model->amount = '100.50'; // Uses currency from attribute or config // String with currency prefix $model->amount = 'EUR 100.50'; $model->amount = 'USD -50.25'; $model->amount = 'GBP 1,234.56'; // Commas and spaces are stripped // Money instance (passed through) $model->amount = Money::of(100.50, 'EUR'); // Null $model->amount = null; ``` -------------------------------- ### MoneyParser Configuration Usage Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md The MoneyParser class defaults to a configured rounding mode if not explicitly provided. ```php class MoneyParser { public static function parse(mixed $value, Currency|string $currency, ?RoundingMode $roundingMode = null): ?Money { // Defaults to config('money.rounding_mode') $roundingMode ??= config('money.rounding_mode', RoundingMode::HalfUp); // ... } } ``` -------------------------------- ### Parse Money Instance Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyParser.md Parses an existing Money instance, returning it directly without modification. The currency parameter is ignored in this case. ```php // Money instance (pass-through) $money = Money::of(100, 'EUR'); MoneyParser::parse($money, 'USD'); // Returns $money (currency parameter ignored) ``` -------------------------------- ### MoneyCast::of() Method Signature Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyCast.md This is the static factory method signature for MoneyCast::of(). It takes a currency code or attribute name and returns a string for model casts. ```php public static function of(string $currencyOrAttribute): string ``` -------------------------------- ### Handling UnknownCurrencyException in Laravel Money Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/errors.md Demonstrates how to catch and handle the UnknownCurrencyException when an invalid currency code is used with MoneyCast or MoneyParser. This is useful for gracefully managing invalid currency inputs. ```php use Elegantly\Money\MoneyCast; // In model definition class Invoice extends Model { protected function casts(): array { return [ 'amount' => MoneyCast::of('INVALID'), // Throws when accessing attribute ]; } } // Accessing the attribute throws $invoice = Invoice::find(1); $amount = $invoice->amount; // Throws UnknownCurrencyException ``` ```php use Elegantly\Money\MoneyParser; MoneyParser::parse('100', 'INVALID'); // Throws UnknownCurrencyException ``` ```php use Elegantly\Money\Rules\ValidMoney; // In a form request, if default_currency is invalid Validator::make(['price' => '100'], ['price' => new ValidMoney()])->validate(); // Throws if config('money.default_currency') is invalid ``` ```php use Brick\Money\Exception\UnknownCurrencyException; use Elegantly\Money\MoneyParser; try { $money = MoneyParser::parse('100', 'INVALID'); } catch (UnknownCurrencyException $e) { // Handle invalid currency logger()->error('Invalid currency: ' . $e->getMessage()); } ``` -------------------------------- ### Set Default Currency Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md Modify the 'default_currency' option in the configuration file to change the default ISO 4217 currency code used by the package. ```php return [ 'default_currency' => 'EUR', ]; ``` -------------------------------- ### validate() Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/ValidMoney.md Runs the validation rule against the attribute value. It parses the value, checks against min/max constraints if provided, and uses a callback to report validation failures. ```APIDOC ## validate() ### Description Runs the validation rule against the attribute value. It parses the value, checks against min/max constraints if provided, and uses a callback to report validation failures. ### Method `public function` ### Parameters #### Parameters - **attribute** (`string`) - Yes - The name of the attribute being validated (e.g., 'price') - **value** (`mixed`) - Yes - The value to validate (any type) - **fail** (`Closure`) - Yes - Callback function to call when validation fails. Receives the error message. ### Details - Parses the value using `MoneyParser::parse()` with the default currency from config. - If parsing returns null: - If `nullable=true`, passes validation (no error). - If `nullable=false`, calls `$fail('money::validation.money')` (not valid money). - If a Money instance is successfully parsed: - If `min` is set and the money is less than min, calls `$fail('money::validation.money_min')`. - If `max` is set and the money is greater than max, calls `$fail('money::validation.money_max')`. - All error messages are translated using Laravel's translation system. ### Error Messages Error messages are loaded from `resources/lang/{locale}/validation.php` and can be customized: - `money::validation.money` — "The value is not a valid money" - `money::validation.money_min` — "The value must be greater than :value" - `money::validation.money_max` — "The value must be less than :value" ``` -------------------------------- ### Configure Rounding Mode Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/configuration.md Set the 'rounding_mode' option to specify how monetary values are rounded when precision exceeds the currency's standard decimal places. Supported modes are from Brick\Math\RoundingMode. ```php use Brick\Math\RoundingMode; return [ 'rounding_mode' => RoundingMode::HalfUp, 'rounding_mode' => RoundingMode::HalfEven, 'rounding_mode' => RoundingMode::Floor, ]; ``` -------------------------------- ### ValidMoney Constructor Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/types.md The ValidMoney constructor defines boundaries for money values. ```APIDOC ## ValidMoney Constructor ### Description Constructs a ValidMoney object with optional minimum and maximum boundaries. ### Method __construct ### Parameters #### Path Parameters - **nullable** (bool) - Optional - Defaults to true. Indicates if the value can be null. - **min** (AbstractMoney | BigNumber | int | string | null) - Optional - Sets the minimum boundary. Accepts null, Money instance, BigNumber instance, integer (major units), or numeric string. - **max** (AbstractMoney | BigNumber | int | string | null) - Optional - Sets the maximum boundary. Accepts null, Money instance, BigNumber instance, integer (major units), or numeric string. ``` -------------------------------- ### Manual MoneyServiceProvider Registration Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyServiceProvider.md Provides the configuration for manually registering the MoneyServiceProvider in Laravel's app.php file if auto-discovery fails. ```php // config/app.php 'providers' => [ Elegantly\Money\MoneyServiceProvider::class, ], ``` -------------------------------- ### Parsing Strings With Currency Code Source: https://github.com/elegantengineeringtech/laravel-money/blob/main/_autodocs/api-reference/MoneyParser.md Illustrates parsing strings that include a currency code. The currency code within the string takes precedence over the provided default currency. ```php MoneyParser::parse('EUR 100.50', 'USD'); // €100.50 (EUR takes precedence) MoneyParser::parse('USD 1234.56', 'EUR'); // $1,234.56 (USD takes precedence) MoneyParser::parse('GBP -50', 'EUR'); // -£50.00 (GBP takes precedence) ```