causeofhell
causeofhell
FFilament
Created by Desmond Njuguna on 10/14/2024 in #❓┊help
Brick Money
Dont cast to money, use an Accessor and a Mutator use the accessorr for table and infolist and the normal attribute to edit/create, in order to reduce code use a trait like this one <?php namespace App\Models\Traits; use Brick\Math\RoundingMode; use Brick\Money\Money; trait HasMoneyAttributes { / * Accessor genérico para obtener el valor monetario. * * @param string $attribute * @return Money */ public function getMoneyInstance(string $attribute): Money { $amountInCents = $this->attributes[$attribute] ?? 0; // Verifica si el modelo tiene la relación 'currency' y si existe el código $currencyCode = $this->currency->code ?? config('app.currency'); return Money::ofMinor($amountInCents, $currencyCode, null, RoundingMode::UP); } / * Mutator genérico para almacenar dinero en centavos. * * @param string $attribute * @param mixed $value */ protected function setMoneyAttribute(string $attribute, $value): void { $currencyCode = $this->currency->code ?? config('app.currency'); if ($value instanceof Money) { $this->attributes[$attribute] = $value->getMinorAmount()->toScale(0, RoundingMode::UP)->toInt(); } else { $this->attributes[$attribute] = (int) Money::of($value, $currencyCode, null, RoundingMode::UP) ->getMinorAmount() ->toScale(0, RoundingMode::UP) ->toInt(); } } }
3 replies