Gaz*_*zer 5 php laravel eloquent
如果我想要一个Eloquent Model类为了实现一个接口而拥有setter和getter,那么下面的方法是否有意义,或者是否有一个"laravel"方法来解决问题
class MyClass extends Model implements someContract
{
public function setFoo($value) {
parent::__set('foo', $value);
return $this;
}
public function getFoo() {
return parent::__get('foo');
}
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*nin 13
您可能正在寻找访问器(getter)和mutators(setter).
Laravel中存取器(getter)的示例:
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
Run Code Online (Sandbox Code Playgroud)
Laravel中mutator(setter)的示例:
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
Run Code Online (Sandbox Code Playgroud)
对于新的 Laravel,你可以在 model 中执行此操作:
/**
* Interact with the user's first name.
*
* @param string $value
* @return \Illuminate\Database\Eloquent\Casts\Attribute
*/
protected function firstName(): Attribute
{
return Attribute::make(
get: fn ($value) => ucfirst($value),
set: fn ($value) => strtolower($value),
);
}
Run Code Online (Sandbox Code Playgroud)
想了解更多吗?参见:(相同的实现)
| 归档时间: |
|
| 查看次数: |
16800 次 |
| 最近记录: |