snoeren-development/laravel-currency-casting

Cast currency attributes, stored as integer, to floats automatically.

v1.9.0 2024-03-25 07:37 UTC

README

Latest version on Packagist Software License Build status Downloads

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!

Installation

You can install the package using Composer:

composer require snoeren-development/laravel-currency-casting

Requirements

This package requires at least PHP 8.2 and Laravel 10.

Usage

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',
    ];

    //
}

Testing

$ composer test

Credits

License

The MIT license. See LICENSE for more information.