8

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?

zx485
  • 28,498
  • 28
  • 50
  • 59
menasoft
  • 135
  • 1
  • 2
  • 12

2 Answers2

17

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();
}
Brian Lee
  • 17,904
  • 3
  • 41
  • 52
15

This creates an array which will contain the original attribute value and what it was changed to:

if (!$model->wasRecentlyCreated) {
    $original = $model->getOriginal();
    $changes = [];

    foreach ($model->getChanges() as $key => $value) {
        $changes[$key] = [
            'original' => $original[$key],
            'changes' => $value,
        ];
    }
}

e.g.

(
    [first_name] => [
        [original] => Kevinn
        [changes] => Kevin
    ]
    [website] => [
        [original] => google.com
        [changes] => google.ca
    ]
)
stardust4891
  • 2,390
  • 1
  • 18
  • 30