foae's avatar
Level 4

Eloquent update ignores setXAttribute

Hello,

I've came across a weird behaviour with Eloquent.

I'm inserting data the usual way, Model::create([array with data and a timestamp]); which comes from an API.

Afterwards, I'm periodically checking if the timestamp has changed local -vs- remote. If there are remote differences, I'll simply pull again the whole result and update the rows running HetrixResult::where('restriction')->update([new array of data]). The problem is that the setXAttribute methods on the model aren't used when I'm running this update.

My build: Laravel 5.3 + sqlite local

Some incoming fillable attributes are inconsistent, so I'm converting them in the model to an appropiate format.

protected $fillable = [
'active', 'name' etc.
];

// I'm converting string to a ints
public function setActiveAttribute($value) {
    $this->attributes['active'] = ($value === 'Active') ? 1 : 0;
}

// I'm storing all names in lowercase for easier read / find in the DB
public function setNameAttribute($value) {
    $this->attributes['name'] = strtolower($value);
}

Yet I find 'Active' and capitalized names in the DB where the update ran.

Any ideas why the set attributes aren't honored on update?

0 likes
2 replies
TerrePorter's avatar
Level 12

@foae I've only seen the setXAttribute work with $model->save() not ->update. You might try a dd in one of them to make sure they are even being called, or maybe try the setAttribute($key, $value) function.

1 like
foae's avatar
Level 4

Yep, using setAttribute($key, $value) worked on both inserts & updates. Thanks!

Please or to participate in this conversation.