Laravel 5.6 - get changed values after updateOrCreate

menasoft picture menasoft · Jun 25, 2018 · Viewed 8.5k times · Source

I have used laravel 5.6 and used the updateOrCreate model to add or update some data.
But I need to get all the values which changed

$q=Userssub::updateOrCreate(
    ['userid' => $uid  ],
    ['model'  => $model]
);

and the result shows like in this image

screen shot of image

How can I get the changes array?
I tried to get it with

$u->changes

and

$u->changes->toarray() 

but both return null.
What can I do to get the changed values?

Answer

DigitalDrifter picture DigitalDrifter · Jun 25, 2018

Eloquent models have two protected arrays, $original and $changes, which contain the attributes as they were when fetched from storage and the attrbirutes which have been modified, respectively.

So you can use getOriginal() and getChanges() and compare the differences.

$model = Model::createOrUpdate([...]);

// wasRecentlyCreated is a boolean indicating if the model was inserted during the current request lifecycle.
if (!$model->wasRecentlyCreated) {
   $changes = $model->getChanges();
}