Transform Eloquent model attribute values when retrieving or setting them. Covers defining accessors and mutators with the Attribute class, and using built-in casts for common type conversions.
Create a protected method on your model whose name corresponds to the attribute in camelCase. The return type must be Illuminate\Database\Eloquent\Casts\Attribute.
<?phpnamespace App\Models;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Model;class User extends Model{ /** * Get the user's first name. */ protected function firstName(): Attribute { return Attribute::make( get: fn (string $value) => ucfirst($value), ); }}
The get closure receives the raw column value. Access the accessor via the snake_case property name.
The get closure accepts a second $attributes argument — an array of all current model attributes. Use it to build a value object from multiple columns.
use App\Support\Address;use Illuminate\Database\Eloquent\Casts\Attribute;protected function address(): Attribute{ return Attribute::make( get: fn (mixed $value, array $attributes) => new Address( $attributes['address_line_one'], $attributes['address_line_two'], ), );}
Eloquent automatically caches value objects returned from accessors so the same instance is returned on repeated access. To cache primitive values as well, call shouldCache().
Attributes that are null will not be cast. Never define a cast (or an attribute) that has the same name as a relationship, and do not cast the model’s primary key.
Specify a format to control JSON serialization output.
protected function casts(): array{ return [ 'published_at' => 'datetime:Y-m-d', ];}
Override serializeDate() to apply a default format to all dates (does not affect database storage format).
use DateTimeInterface;protected function serializeDate(DateTimeInterface $date): string{ return $date->format('Y-m-d');}
Use immutable_datetime to receive a CarbonImmutable instance instead of Carbon. Operations on immutable objects return new instances, preventing accidental mutation of shared state.