Laravel Money.
Note: This project abstracts MoneyPHP
Run the following command from you terminal:
composer require cknow/laravel-moneyor add this to require section in your composer.json file:
"cknow/laravel-money": "^8.0"then run composer update
use Cknow\Money\Money;
echo Money::USD(500); // $5.00
echo Money::USD(500, true); // $500.00 force decimalsThe defaults are set in config/money.php. Copy this file to your own config directory to modify the values. You can publish the config using this command:
php artisan vendor:publish --provider="Cknow\Money\MoneyServiceProvider"This is the contents of the published file:
…See MoneyPHP for more information
…class MyFormatter implements \Money\MoneyFormatter
{
/**
* Formats a Money object as string.
*/
public function format(\Money\Money $money): string
{
return 'My Formatter';
}
}
Money::USD(500)->formatByFormatter(new MyFormatter()); // My FormatterBelow is a list of all available validation rules and their function:
The field under validation must be a valid currency.
Validator::make([
'currency1' => 'USD',
'currency2' => 'EUR',
'currency3' => new \Money\Currency('BRL'),
], [
'currency1' => new \Cknow\Money\Rules\Currency(),
'currency2' => new \Cknow\Money\Rules\Currency(),
'currency3' => 'currency',
]);The field under validation must be a valid money.
Validator::make([
'money1' => '$10.00'
'money2' => '€10.00',
'money3' => 'R$10,00',
'money4' => '$10.00'
'money5' => '€10.00',
'money6' => 'R$10,00',
], [
'money1' => new \Cknow\Money\Rules\Money(),
'money2' => new \Cknow\Money\Rules\Money('EUR'), // forcing currency
'money3' => new \Cknow\Money\Rules\Money('BRL', 'pt_BR'), // forcing currency and locale
'money4' => 'money',
'money5' => 'money:EUR', // forcing currency
'money6' => 'money:BRL,pt_BR', // forcing currency and locale
]);At this stage the cast can be defined in the following ways:
…In the example above, if the model attribute currency is null,
the currency defined in the package configuration is used instead.
Setting money can be done in several ways:
$model->money = 10; // 0.10 USD or any other currency defined
$model->money = 10.23; // 10.23 USD or any other currency defined
$model->money = 'A$10'; // 10.00 AUD
$model->money = '1,000.23'; // 1000.23 USD or any other currency defined
$model->money = '10'; // 0.10 USD or any other currency defined
$model->money = Money::EUR(10); // 0.10 EURWhen we pass the model attribute holding the currency, such attribute is updated as well when setting money:
$model->currency; // null
$model->money = '€13';
$model->currency; // 'EUR'
$model->money->getAmount(); // '1300'……No open issues yet, or sync has not completed.