ตัวแปรสำหรับการจัดการ Attributes ใน Laravel Model ประกอบด้วย
- $fillable - เป็นตัวแปรที่กำหนดว่า Attributes ใดสามารถแก้ไขค่าได้บ้าง
- $cast - เป็นตัวแปรที่กำหนดว่า Attributes ใดต้องเปลี่ยนประเภทตัวแปรบ้าง ซึ่งประเภทตัวแปร ประกอบด้วย integer, real, float, double, decimal:<digits>, string, boolean, object, array, collection, date, datetime และ timestamp
- $dates - เป็นตัวแปรที่กำหนดว่า Attributes ใดต้องถูกเปลี่ยนประเภทเป็น datetime บ้าง ซึ่ง attribute ดังกล่าวจะถูก cast เป็น Carbon instance
- $hidden - เป็นตัวแปรที่กำหนดว่า Attributes ใดต้องถูกตัดออก เมื่อมีการแปลง Model ไปเป็น JSON
- $appends - เป็นตัวแปรที่กำหนดว่า Attributes ใดต้องถูกเพิ่มเข้าไป เมื่อมีการแปลง Model ไปเป็น JSON
protected $fillable = [
'title_name',
'first_name',
'last_name',
'is_admin',
'username',
'password',
'login_at',
];
protected $casts = [
'is_admin' => 'boolean',
];
protected $dates = [
'login_at',
];
protected $hidden = [
'password',
];
protected $appends = ['full_name'];
Function สำหรับการจัดการ Attributes ใน Laravel Model มี 2 ประเภท คือ- Accessors - เป็น Function ที่ถูกเรียก เมื่อมีการดึงค่า Attribute นั้นๆ ซึ่งจะมีรูปแบบ function ดังนี้
public function get{AttributeName}Attribute() { return $this->{attribute_name}; } - Mutators - เป็น Function ที่ถูกเรียก เมื่อมีการแก้ไขค่า Attribute นั้นๆ ซึ่งจะมีรูปแบบ function ดังนี้
public function set{AttributeName}Attribute($value) { $this->attributes['{attribute_name}'] = $value; }
{AttributeName}เป็นชื่อของ Attribute นั้นๆในรูปแบบของ Camel case{attribute_name}เป็นชื่อของ Attribute เดิม
public function getFullNameAttribute() {
return "{$this->first_name} {$this->last_name}";
}
ตัวอย่างของ Mutatorspublic function setFirstNameAttribute($value) {
$this->attributes['first_name'] = strtolower($value);
}
หมายเหตุ: การเพิ่ม Custom Attributes ใน Laravel Model ก็คือ การเพิ่ม Accessor ของ Attribute ใหม่นั่นเอง
No comments:
Post a Comment