Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.6 - get changed values after updateOrCreate

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?

like image 461
menasoft Avatar asked Jun 25 '18 17:06

menasoft


2 Answers

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();
}
like image 108
Brian Lee Avatar answered Sep 17 '22 10:09

Brian Lee


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
    ]
)
like image 22
stardust4891 Avatar answered Sep 21 '22 10:09

stardust4891