offizium-berndstorath's avatar

updateOrCreate. But only update timestamps if changed

Hello,

I have code that calls Model::updateOrCreate. It works perfectly fine. But I noticed it updates the updated_at timestamp every time. Even if no actual change happened.

Is there a way to use this function but only update updated_at if the new data is different? or is there a good alternative

0 likes
2 replies
Snapey's avatar

does your data include another datetime column?

Snapey's avatar

Just to explain that question. I had this issue when saving a date time that came from an API

The incoming value contained milliseconds.

mysql does not by default store milliseconds so is always returned as .000

When the record is being updated, eloquent sees an incoming value ending eg, .123 and since this is different to .000 it updates the row (with the same data)

I got around it by formatting the incoming date to strip the ms

$event->EventDateTime = Carbon::parse($event->EventDateTime)->format('Y-m-d H:i:s');

The milliseconds were irrelevant in my case, your application may have a requirement for them

Please or to participate in this conversation.