Accessors, Mutators & Attribute Casting
Accessors transform attribute values when you read them. Mutators transform values when you set them. Casts automatically convert between database types and PHP types (JSON ↔ array, string ↔ datetime). These keep transformation logic in the model, not scattered across controllers.
Accessors & Mutators (Laravel 11+)
use Illuminate\Database\Eloquent\Casts\Attribute;
class User extends Model
{
// Accessor — transform when reading
protected function name(): Attribute
{
return Attribute::make(
get: fn (string $value) => ucwords($value),
);
}
// $user->name returns 'John Doe' even if stored as 'john doe'
// Mutator — transform when setting
protected function password(): Attribute
{
return Attribute::make(
set: fn (string $value) => bcrypt($value),
);
}
// $user->password = 'secret' automatically hashes it
// Combined accessor + mutator
protected function email(): Attribute
{
return Attribute::make(
get: fn (string $value) => strtolower($value),
set: fn (string $value) => strtolower($value),
);
}
// Attribute casting (in $casts property)
protected $casts = [
'is_admin' => 'boolean',
'options' => 'array', // JSON ↔ PHP array
'birthday' => 'date', // String ↔ Carbon date
'email_verified_at' => 'datetime',
];
}Tip
Tip
Practice Accessors Mutators Attribute Casting in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Middleware = filters that run before/after your controller logic
Practice Task
Note
Practice Task — (1) Write a working example of Accessors Mutators Attribute Casting from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Accessors Mutators Attribute Casting is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready laravel code.