What happens when updateOrCreate can't update or create?
Hi
I'm updating (or creating) lots of records from an API, but I would like a way of catching when records can't update or create so I can save them for future auditing in case of problems.
Is there a way to find out when this happens, please?
@tykus I don't have an example I'm afraid. I'm just trying to cover my backside in the event that the data that can't be updated or created is saved so I can reverse engineer why in case of problems. I need to try and cover all eventualities.
@anatomic no, I was asking earlier In what circumstances does updateOrCreate fail; and not updating an existing record because has the same attributes is not a failure.
What you can do is check two things; (i) if the Model wasRecentlyCreated (it was just created) and (ii) if an existing record was found, then wasChanged will inform if it was changed. So, if both are false, this is effectively the "failure" scenario:
$model = Model::updateOrCreate([/* unique attributes */], [/* other attributes */]);
if (! $model->wasRecentlyCreated && ! $model->wasChanged()) {
\Log::info('Model was neither updated nor created', [
'model_id' => $model->id, // the found model
'attributes' => $attributes // the 'new' attributes
]);
}
@tykus Sorry, I think it's just a misuse of words on my part. I've never said it fails (using the word catching unfortunately implied that!), it works exactly as I expect. I just wanted to know how/if I can find when it doesn't update or create (because its not unique) and record that.
Thanks for your help, I think your solution should do the trick. :)
@Sinnbeck Thanks, I've considered this, but so far the data I receive from the API means I have to insert one record at a time, which is not a huge issue as it's set up as a job to run on the schedule.