Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tyler-shaw's avatar

Can I check if a model attribute has changed to same value?

My table has a price field and a price_updated_at field. I would like to automatically update the price_updated_at field whenever a change to the price is saved - even if it's just set back to the same value. I'm looking for something like isDirty that can tell me if an attribute has been touched, even if its value hasn't changed.

Edit: I'm just overthinking things - going to go with the simple solution of setting it manually instead of trying to abstract the price_updated_at field away.

0 likes
4 replies
willvincent's avatar
Level 54

Is there some way I can hook into the updating of a model so I can detect these changes?

Why yes, yes there is... Events

Within the event you can then use ->getOriginal($fieldname) to get the previous value. So in your case, for price:

if ($obj->price != $obj->getOriginal('price')) {
  // A change to the price has occurred.
  $obj->price_updated_at = Carbon::now()->toDateTimeString();
}

EDIT: looking at your scenario again, it looks like regardless if the price has changed or not you want to update the time? So basically any time a price is updated from this external API you want the time updated, yes? Why not just do that at that time? Cron runs, and sees an old price, so a call is made to a 3rd party API.. price is updated (to same, or new value) .. update price_updated_at field to current time, save. Unless I'm misunderstanding something, it sounds like you're overcomplicating things by not just updating the timestamp when you update the price.

4 likes
tyler-shaw's avatar

Why yes, yes there is... Events

Thanks for the response. I'm actually already using the saving event. I was hoping there was something like isDirty that let's me know if the field has been updated at all, not just if it's value has been changed. Hope that makes sense.

EDIT: looking at your scenario again, it looks like regardless if the price has changed or not you want to update the time? So basically any time a price is updated from this external API you want the time updated, yes? Why not just do that at that time? Cron runs, and sees an old price, so a call is made to a 3rd party API.. price is updated (to same, or new value) .. update price_updated_at field to current time, save.

I could definitely do that. I was just hoping to abstract it away so that any logic related to the price_updated_at field can be tucked away into a single observer and forgotten about.

Please or to participate in this conversation.