Money Cast (currency)

Hello.
I need to manage many money fields (usually Euros only) and I have a app\Casts\MoneyCast.php working fine with this content:
<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;

class MoneyCast implements CastsAttributes
{
    /**
     * Cast the given value.
     *
     * @param  array<string, mixed>  $attributes
     */
    public function get(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        return round(floatval($value) / 100, precision: 2);
    }

    /**
     * Prepare the given value for storage.
     *
     * @param  array<string, mixed>  $attributes
     */
    public function set(Model $model, string $key, mixed $value, array $attributes): mixed
    {
        return round(floatval($value) * 100);
    }
}

And then, in the different Models I have:
protected $casts = [
        'previous_economic_assets' => MoneyCast::class,
    ];

With as many fields as I need to be casted.

The field in the table is storing the data in and integer field. The problem is that user can type more than 2 decimals.

The problem is that I would like to use a mask (thousandseparator = . and decimalseparator , limit decimals to 2 and add € symbol at the end).
I have seen other people have tried to create a customized MoneyInputField but I do not know where to begin.

Any ideas of how can I customize my Money Cast to implement the Mask and suffix?
Or, should it be better to create a custom input field for forms? I must consider that I do not want to repeat masking in every money input field I use in forms (they are really a big bunch) and I would like to have something more "automatic" if possible.

Tks.

By the way, if possible, users here type . or , for the decimal places (should admit both) although VISUALLY only comma is accepted for decimals.
Was this page helpful?