Skip model accessor

后端 未结 4 850
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 13:56

I got a model called Run which contains this method:

public function getNameAttribute($name){
    if($name == \'Eendaags\')
        return $this->race_edition         


        
4条回答
  •  梦谈多话
    2021-01-31 14:49

    this is the correct way

    // that skips mutators
    $model->getOriginal('name');
    

    https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html#method_getOriginal

    Edit: Careful!

    As Maksym Cierzniak explained in the comments, getOriginal() doesn't just skip mutators, it also returns the "original" value of the field at the time the object was read from the database. So if you have since modified the model's property, this won't return your modified value, it will still return the original value. The more consistent and reliable way to get the un-mutated value from within the model class is to retrieve it from the attributes property like this:

    $this->attributes['name']
    

    But be aware that attributes is a protected property, so you can't do that from outside the model class. In that case, you can use

    $model->getAttributes()['name']`
    

    or Maksym's technique from his comment below.

提交回复
热议问题