Accessor biến đổi dữ liệu lúc đọc, mutator biến đổi lúc ghi.
Cả hai khai báo bằng Attribute::make():
php
// accessor — viết hoa chữ cái đầu khi truy cập
protected function name(): Attribute {
return Attribute::make(get: fn($value) => ucfirst($value));
}
// mutator — chuyển chữ thường khi lưu
protected function email(): Attribute {
return Attribute::make(set: fn($value) => strtolower($value));
}Gán $user->email = "JOHN@EXAMPLE.COM" sẽ lưu xuống dạng chữ thường, còn echo $user->name hiển thị viết hoa dù DB lưu chữ thường.
Accessor/mutator gom logic định dạng về một chỗ.