menasoft
menasoft

Reputation: 145

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?

Upvotes: 8

Views: 18363

Answers (2)

stardust4891
stardust4891

Reputation: 2550

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
    ]
)

Upvotes: 18

Brian Lee
Brian Lee

Reputation: 18187

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();
}

Upvotes: 19

Related Questions