Accessor và Mutator là gì? Ứng dụng trong thực tế?
Accessor và Mutator là gì? Ứng dụng trong thực tế?
Trong Eloquent:
$user->full_name).$user->password = '...').Attributeuse Illuminate\Database\Eloquent\Casts\Attribute;
class User extends Model
{
protected function name(): Attribute
{
return Attribute::make(
get: fn (string $value) => ucwords($value), // accessor
set: fn (string $value) => trim($value), // mutator
);
}
// Accessor ảo, không có cột trong DB
protected function fullName(): Attribute
{
return Attribute::make(get: fn () => "{$this->first_name} {$this->last_name}");
}
protected $appends = ['full_name']; // để xuất hiện khi toArray()/JSON
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.