Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Laravel Advanced & Architecture 5-8 Years (Senior) Medium Production Scenario

How do you implement Custom Eloquent Casts with Value Objects in modern Laravel?

Real-World Scenario / Incident Description

A fintech app handles multi-currency amounts (USD, EUR, JPY) and needs to avoid floating point precision errors by casting database integers to immutable `Money` Value Objects.

346 views • Updated 1 month ago

Implementing CastsAttributes

class MoneyCast implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): ?Money
    {
        return $value !== null ? new Money((int) $value, $attributes['currency'] ?? 'USD') : null;
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): array
    {
        if ($value instanceof Money) {
            return [$key => $value->getAmountInCents(), 'currency' => $value->getCurrency()];
        }
        return [$key => (int) $value];
    }
}
Related Concepts: #Eloquent #Custom Casts #Value Objects #DDD #Fintech