Adding Setters and Getters to Laravel Model

倾然丶 夕夏残阳落幕 提交于 2019-12-22 07:09:46

问题


If I want an Eloquent Model class to have setters and getters for the sake of implementing an interface does the following approach make sense or is there a 'laravel' approach to the problem

class MyClass extends Model implements someContract
{

  public function setFoo($value) {
      parent::__set('foo', $value);
      return $this;
  }

  public function getFoo() {
      return parent::__get('foo');
  }
}

回答1:


You are probably looking for accessors (getters) and mutators (setters).

Example of an accessor (getter) in Laravel:

public function getFirstNameAttribute($value)
{
    return ucfirst($value);
}

Example of a mutator (setter) in Laravel:

public function setFirstNameAttribute($value)
{
    $this->attributes['first_name'] = strtolower($value);
}


来源:https://stackoverflow.com/questions/40337400/adding-setters-and-getters-to-laravel-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!