Introduction
Accessors, mutators, and attribute casting let you transform Eloquent attribute values when you retrieve or set them on model instances.- Accessor — transforms a raw database value before it reaches your application
- Mutator — transforms a value set by your application before it is stored in the database
- Cast — declaratively defines type conversion without writing accessor/mutator methods
Defining an accessor
Create aprotected method on your model whose name corresponds to the attribute in camelCase. The return type must be Illuminate\Database\Eloquent\Casts\Attribute.
get closure receives the raw column value. Access the accessor via the snake_case property name.
To include computed accessor values in JSON or array output, add them to the model’s
$appends property.Building value objects from multiple attributes
Theget closure accepts a second $attributes argument — an array of all current model attributes. Use it to build a value object from multiple columns.
Accessor caching
Eloquent automatically caches value objects returned from accessors so the same instance is returned on repeated access. To cache primitive values as well, callshouldCache().
withoutObjectCaching().
Defining a mutator
Add aset argument to Attribute::make(). Accessor and mutator can be defined in the same method.
set closure.
Mutating multiple attributes
Return an array from theset closure to update multiple database columns at once.
Attribute casting
Casts let you declare type conversions without writing accessor/mutator methods. Return an array from the model’scasts() method.
Built-in cast types
Stringable casting
UseAsStringable to cast an attribute to a fluent Illuminate\Support\Stringable object.
Array and JSON casting
Thearray cast automatically deserializes JSON columns to PHP arrays on retrieval and serializes them back on save.
-> operator to update a single JSON key.
AsArrayObject and AsCollection
The standardarray cast returns a primitive type — directly modifying an offset triggers a PHP error. Use AsArrayObject or AsCollection to avoid this.
using().
Date casting
created_at and updated_at are cast to Carbon by default. Cast additional date columns the same way.
serializeDate() to apply a default format to all dates (does not affect database storage format).
Enum casting
Cast attributes to PHP 8.1+ Backed Enums.Casting arrays of enums
Store multiple enum values in a single column usingAsEnumCollection.
Query time casting
Apply casts dynamically during a query withwithCasts().
Custom casts
You can create your own cast classes by implementing theCastsAttributes interface with get and set methods.
Custom casts deep dive
Learn how to implement CastsAttributes, use Value Object patterns, inbound casting, and Castables.
Related pages
Eloquent API resources
Transform Eloquent models into consistent JSON API responses using resource classes.