Laravel check if updateOrCreate performed an update

Viewed 27533

I have the following code in my controller:

for($i=0; $i<$number_of_tourists; $i++) {
    $tourist = Tourist::updateOrCreate([
        'doc_number' => $request['doc_number'][$I]
    ],
    $tourist_to_update);
}

Each time updateOrCreate runs, it does 1 of 3 things:

  1. Updates the model instance; OR

  2. Creates and saves a new one; OR

  3. Leaves everything unchanged (if model with such values already exists)

I need to check if updateOrCreate has done the first one (updated) and then execute some code.

How can I do it?

5 Answers

Okay so I couldn't find a good answer for my scenario.

I was using: $this->created_at == $this->updated_at however I would sometimes update the record later in the request, which meant that 20% of the time the created_at and updated_at were about 1ms out.

To combat this I created something a little more relaxed which allows an extra second between creation and modification.

public function getRecentlyCreatedAttribute()
{
    return $this->wasRecentlyCreated || $this->created_at == $this->updated_at || $this->created_at->diffInSeconds($this->updated_at) <= 1;
}

I can now call $this->recentlyCreated which will return true if there is a small difference in time (1 second).

Tbh this is the second time I've needed this in a project, I'm posting as I just ended up googling it and coming back to this thread looking for the same answer.

If someone has a more elegant solution, hmu.

The model attribute 'wasRecentlyCreated' would only be 'true' if it has just been created.

There is property named 'changes' in model (it is an array), that determines whether the model has been updated with new values or it has been saved as is without making any changes to its attribute.

Check the following code snippet:

       // Case 1 :  Model Created
        if ($model->wasRecentlyCreated) {

        } else { // Case 2 :  Model Updated

            if (count($model->changes)) { // model has been assigned new values to one of its attributes and saved successfully

            } else { // model has NOT been assigned new values to one of its attributes and saved as is

            }

        }
Related