Laravel Money

repository·main·Indexed 21 days ago

https://github.com/cknow/laravel-money

A wrapper around MoneyPHP for the Laravel framework. It provides seamless integration through Eloquent casts (MoneyDecimalCast, MoneyIntegerCast, MoneyStringCast), custom validation rules for currency and money, Blade directives for formatting and aggregation, and global helpers. The library supports money arithmetic, comparisons, and custom formatting via the MoneyFormatter interface.

Tokens
5.4K
Snippets
25
Records
28
Agent score
77%

What's inside laravel-money

  1. Use Laravel Model Casts for Money

    main

    Integrate money handling directly into your Eloquent models using the provided casts. This allows you to store money as integers, decimals, or strings in the database while interacting with them as money objects or formatted values in your application.

    use Cknow\Money\Casts\MoneyDecimalCast;
    use Cknow\Money\Casts\MoneyIntegerCast;
    use Cknow\Money\Casts\MoneyStringCast;
    
    protected $casts = [
        'money' => MoneyDecimalCast::class, // Uses default currency from config
        'money' => MoneyIntegerCast::class . ':AUD', // Forces AUD
        'money' => MoneyStringCast::class . ':currency', // Uses 'currency' attribute on model
    ];
  2. Configure Laravel Money

    main

    Publish the configuration file to config/money.php to customize locales, default currencies, and supported currency lists (ISO, Bitcoin, or custom).

    php artisan vendor:publish --provider="Cknow\Money\MoneyServiceProvider"
  3. Basic Usage of the Money class

    main

    Use the Cknow\Money\Money class to create money instances using static methods named after currency codes. The amount passed is in the smallest unit (e.g., cents for USD).

    use Cknow\
    Money\Money;
    
    echo Money::USD(500); // $5.00
    echo Money::USD(500, true); // $500.00 force decimals
  4. Implement a Custom Money Formatter

    main

    You can create custom formatting logic by implementing the \Money\MoneyFormatter interface and passing it to the formatByFormatter() method.

    class MyFormatter implements \Money\MoneyFormatter
    {
        public function format(\Money\Money $money): string
        {
            return 'My Formatter';
        }
    }
    
    Money::USD(500)->formatByFormatter(new MyFormatter()); // My Formatter
  5. Perform Money Arithmetic and Comparisons

    main

    The Money class provides methods for arithmetic operations (add, subtract, multiply, divide, mod), sign manipulation (absolute, negative), and comparisons (equals, greaterThan, lessThan, etc.). It also supports aggregation functions like min, max, avg, and sum.

    use Cknow\Money\Money;
    
    // Arithmetic
    Money::USD(500)->add(Money::USD(500)); // $10.00
    Money::USD(500)->subtract(Money::USD(400)); // $1.00
    Money::USD(500)->multiply(2); // $10.00
    Money::USD(1000)->divide(2); // $5.00
    
    // Comparisons
    Money::USD(500)->equals(Money::USD(500)); // true
    Money::USD(500)->greaterThan(Money::USD(100)); // true
    
    // Aggregation
    Money::sum(Money::USD(100), Money::USD(200), Money::USD(300)); // Money::USD(600)
  6. Format and Parse Money

    main

    The library provides several ways to format money as strings (using Intl, currency symbols, or decimals) and parse strings back into Money instances (via Intl, decimal, or Bitcoin formats).

    use Cknow\Money\Money;
    
    // Formatting
    Money::USD(500)->format(); // $5.00
    Money::USD(500)->formatByIntl(); // $5.00
    
    // Parsing
    Money::parse('$1.00'); // Money::USD(100)
    Money::parseByDecimal('1.00', 'USD'); // Money::USD(100)
  7. Configure the ISO currencies path

    main
    The ISOCurrencies class loads its currency definitions from a file specified in the Laravel configuration. You can customize the location of this file by setting the money.isoCurrenciesPath configuration key. This is useful if you need to provide a custom list of ISO currencies or override the default implementation.
  8. Use Money Helpers

    main

    The package provides global helper functions for quick access to money operations without needing to call the Money class directly.

    currency(); // Default currency from config
    currency('USD');
    
    money(500); // Default currency
    money(500, 'USD');
    
    money_parse('$5.00'); // Money::USD(500)
    
    // Aggregation helpers
    money_sum(money(100, 'USD'), money(200, 'USD'));
  9. Validate Currency and Money in Laravel Requests

    main

    Use the following validation rules in your Laravel controllers or FormRequests:

    • currency: Validates that a field is a valid currency code.
    • money: Validates that a field is a valid money string. You can force a specific currency using money:CURRENCY or a locale using money:CURRENCY,LOCALE.
    // Currency validation
    Validator::make(['c' => 'USD'], ['c' => new \Cknow\Money\Rules\Currency()]);
    
    // Money validation
    Validator::make(['m' => '$10.00'], ['m' => 'money:EUR,pt_BR']);