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’scasts 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, implementCastsAttributes.
The interface
$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.app/Casts/AsMoney.php. The following implementation converts an integer amount stored in the database into a Money Value Object.
$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 combinesaddress_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. UseCastsInboundAttributes.
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 ,.
Castables — letting the Value Object own its cast
A Value Object that implementsCastable declares which cast class to use via a static castUsing method. The model does not need to know about the cast class at all.
Merging casts at runtime
To apply a cast only for a specific query or request, usemergeCasts.
Next steps
Eloquent Observers
Learn how to hook into model lifecycle events with Observer classes.