Accessor biến đổi dữ liệu khi đọc, mutator biến đổi khi ghi. Định nghĩa accessor: protected function name(): Attribute { return Attribute::make(get: fn($value) => ucfirst($value)); } tự động viết hoa chữ cái đầu khi truy cập. Mutator: protected function email(): Attribute { return Attribute::make(set: fn($value) => strtolower($value)); } chuyển sang chữ thường khi lưu.
Ví dụ: $user->email = "JOHN@EXAMPLE.COM" lưu thành chữ thường, echo $user->name hiển thị viết hoa dù lưu là chữ thường. Accessor/mutator tập trung logic định dạng vào một chỗ.
Accessors transform data when reading, mutators transform when writing. Define accessor: protected function name(): Attribute { return Attribute::make(get: fn($value) => ucfirst($value)); } automatically capitalizes name when accessed. Mutator: protected function email(): Attribute { return Attribute::make(set: fn($value) => strtolower($value)); } converts to lowercase on save.
Example: $user->email = "JOHN@EXAMPLE.COM" stores as lowercase, echo $user->name (John) displays capitalized even if stored as john. Accessors/mutators centralize formatting logic.