What are custom Eloquent cast types in Laravel?
Why Interviewers Ask This
Senior Laravel engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.
Answer
Custom cast types allow you to define reusable type transformations for Eloquent model attributes. Implement CastsAttributes: class MoneyCast implements CastsAttributes { public function get($model, $key, $value, $attributes) { return new Money($value, $attributes["currency"]); } public function set($model, $key, $value, $attributes) { return ["amount" => $value->getAmount(), "currency" => $value->getCurrency()]; } }. Register in model: protected $casts = ["price" => MoneyCast::class]. Inbound-only casts (transform only on set) implement CastsInboundAttributes. Castable classes implement Castable with a castUsing() method that returns the cast class name. Use cases: Money value objects, encrypted fields, custom date formats, geographic coordinates. Custom casts make the model the single source of truth for data transformations, keeping controllers and services clean.
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.
Previous
What is deferred loading with lazy collections in Laravel?
Next
What is query logging and debugging in Laravel?