Easily use Brick/Money in your Laravel app.
- MoneyCast: Cast your model attributes to
Brick\Money\Money
- MoneyParse: Parse strings and other types to
Brick\Money\Money
- ValidMoney: Money validation rule
The namespace has been updated: from Finller\Money
to Elegantly\Money
.
You can simply do a search+replace.
You can install the package via Composer:
composer require elegantly/laravel-money
You can publish the config file with:
php artisan vendor:publish --tag="money-config"
This is the content of the published config file:
return [
'default_currency' => 'USD',
];
If you store the currency in a table column alongside the amount value, you can specify the column name like this:
use Elegantly\Money\MoneyCast;
/**
* @property ?Money $price
* @property ?string $currency
**/
class Invoice extends Model {
protected $casts = [
'price' => MoneyCast::class . ':currency'
];
}
You can cast your money to a specific currency using the currency code instead of the column name.
use Elegantly\Money\MoneyCast;
/**
* @property ?Money $price
* @property ?Money $cost
**/
class Invoice extends Model {
protected $casts = [
'cost' => MoneyCast::class . ':EUR',
'price' => MoneyCast::class . ':USD'
];
}
You can parse any string/int/float to a money instance using MoneyParser
.
Here are some examples of the expected behavior:
use Elegantly\Money\MoneyParser;
MoneyParser::parse(null, 'EUR'); // null
MoneyParser::parse(110, 'EUR'); // 110.00€
MoneyParser::parse(100.10, 'EUR'); // 100.10€
MoneyParser::parse('', 'EUR'); // null
MoneyParser::parse('1', 'EUR'); // 1.00€
MoneyParser::parse('100.10', 'EUR'); // 100.10€
Using ValidMoney
within Livewire:
namespace App\Livewire;
use Elegantly\Money\Rules\ValidMoney;
use Illuminate\Foundation\Http\FormRequest;
class CustomComponent extends Component
{
#[Validate([
new ValidMoney(nullable: false, min: 0, max: 100)
])]
public ?int $price = null;
}
Using ValidMoney
within a form request:
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
)
],
];
}
}
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.