Transform model attributes on read/write with Accessors, Mutators, and built-in $casts.
Mutators and Accessors (Casts)
class User extends Model {
// Accessor — transform when getting
protected function name(): Attribute {
return Attribute::make(
get: fn($value) => ucfirst($value),
);
}
// Mutator — transform when setting
protected function password(): Attribute {
return Attribute::make(
set: fn($value) => bcrypt($value),
);
}
// Accessor + Mutator
protected function fullName(): Attribute {
return Attribute::make(
get: fn($v, $attrs) => $attrs["first_name"]." ".$attrs["last_name"],
set: fn($v) => ["first_name" => explode(" ",$v)[0],
"last_name" => explode(" ",$v)[1]],
);
}
// Built-in casts
protected $casts = [
"is_admin" => "boolean",
"permissions" => "array", // JSON column ↔ PHP array
"published_at" => "datetime",
"price" => "decimal:2",
];
}