Skip to main content

What are casts?

Eloquent casts convert raw database values to PHP types when you read them, and convert them back when you write. You define them in the model’s casts method.

Built-in cast types

AsArrayObject and AsCollection are implemented as custom casts internally so that individual offsets can be modified directly.

Creating a custom cast

When the built-in types do not cover your needs, implement CastsAttributes.

The interface

The $attributes parameter gives you access to every column on the model, which makes multi-column Value Object casts possible.

Basic example

Generate a stub with Artisan.
This creates app/Casts/AsMoney.php. The following implementation converts an integer amount stored in the database into a Money Value Object.
Apply the cast to a model.
Now $order->price returns a Money instance.

Value Object casts

A Value Object cast maps multiple database columns to a single PHP object.

Example: Address cast

This cast combines address_line_one and address_line_two into a single Address Value Object.
When set returns an array, Eloquent uses the array keys as column names and writes each value to the corresponding column. For single-column casts, return a scalar value.

Value Object caching

Cast Value Objects are cached by Eloquent. Accessing the same attribute twice returns the same object instance. To disable this behavior, add the $withoutObjectCaching property to your cast class.

Inbound casts (write-only)

An inbound cast transforms a value only when it is written to the database. Reading returns the raw stored value. Use CastsInboundAttributes. Hashing is the canonical example — you hash a password when storing it, but you never reverse the transformation when reading.

Cast parameters

Pass parameters to a cast class by appending them to the class name with : and ,.
Parameters are passed to the cast class constructor.

Castables — letting the Value Object own its cast

A Value Object that implements Castable declares which cast class to use via a static castUsing method. The model does not need to know about the cast class at all.
The model references the Value Object class directly.
Combine Castable with an anonymous class to keep the Value Object and its cast logic in a single file.

Merging casts at runtime

To apply a cast only for a specific query or request, use mergeCasts.

Next steps

Eloquent Observers

Learn how to hook into model lifecycle events with Observer classes.
Last modified on March 28, 2026