15

Using the method updateOrCreate, is there a way to know which if a record was updated or created?

UPDATE: I need to use this feature to return 201, for created record, or 204 for updated record.

Thank you.

vlauciani
  • 1,010
  • 2
  • 13
  • 27

1 Answers1

18

Since updateOrCreate returns the model instance. https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Builder.php#L374

You can check that a record was recently created using: $instance->wasRecentlyCreated https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Eloquent/Model.php#L1593

Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
  • What if the record exists, but actually wasn't updated? – Hlorofos May 29 '18 at 19:48
  • Check if the instance of the model is dirty using `$instance->isDirty()` – Oluwafemi Sule May 29 '18 at 20:11
  • @OluwafemiSule, if calling `isDirty` after the `updateOrCreate` or `firstOrCreate` on the returned Model, it is my understanding that the Model being checked will always return `false` as the operations will have already been performed to update or create the model. I think another property needs to be added, `wasRecentlyUpdated`. This property could be updated at least once, within the `performUpdate` function. There may be other functions, like the `save` function, where updating the property may make sense. – Todd May 23 '21 at 16:14