Example 5-34. Decorating a preexisting column using Eloquent accessors
// Model definition:classContactextendsModel{publicfunctiongetNameAttribute($value){return$value ?:'(No name provided)';}}// Accessor usage:$name=$contact->name;
但是我们也可以使用访问器来定义数据库中从未存在的属性,例如5-35。
Example 5-35. Defining an attribute with no backing column using Eloquent accessors
// Model definition:classContactextendsModel{publicfunctiongetFullNameAttribute(){return$this->first_name .''.$this->last_name;}}// Accessor usage:$fullName=$contact->full_name;
Example 5-36. Decorating setting the value of an attribute using Eloquent mutators
// Defining the mutator
class Order extends Model {
public function setAmountAttribute($value) {
$this->attributes['amount'] = $value > 0 ? $value : 0;
}
}
// Using the mutator
$order->amount = '15'
Example 5-37. Allowing for setting the value of a nonexistent attribute using Eloquent mutators
// Defining the mutator
class Order extends Model {
public function setWorkgroupNameAttribute($workgroupName) {
$this->attributes['email'] = "{$workgroupName}@ourcompany.com";
}
}
// Using the mutator
$order->workgroup_name = 'jstott';
Example 5-38. Using attribute casting on an Eloquent model