This package adds a Laravel model cast. This way you can cast any attribute that stores a currency, with an integer value in the database, to a float automatically!
You can install the package using Composer:
composer require snoeren-development/laravel-currency-casting
This package requires at least PHP 7.4 and Laravel 6.
Store your currency as an integer value in the database. This is more accurate than storing it as a float.
Add the attributes you'd like to see cast to the casts
array and assign the Currency
class to it. If you need more than the default 2 digits currency usually has, you can append the number of digits you need after the currency class like in the example below. Just make sure your database column can handle the larger integer it produces.
<?php
use Illuminate\Database\Eloquent\Model;
use SnoerenDevelopment\CurrencyCasting\Currency;
class Plan extends Model
{
//
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'price' => Currency::class,
'price_with_digits' => Currency::class . ':4',
];
//
}
$ composer test
The MIT license. See LICENSE for more information.