Trung BìnhLaravel iconLaravel

Accessor và Mutator trong Eloquent là gì?

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ỗ.

Xem toàn bộ Laravel cùng filter theo level & chủ đề con.

Mở danh sách Laravel