Elliot
Elliot

Reputation: 1616

Detect specific change during Eloquent Updated event

Using Eloquent Events/Observers, is it possible to detect which properties were updated within an Update event? Or, can you gain access to the previous/new values to do a comparison?

I'm finding the only solution is to manually fire events by detecting the specific field exists in the validated request data, in the controller.

Upvotes: 10

Views: 3958

Answers (2)

reza
reza

Reputation: 134

You can use the following methods:

    static::updated(function (User $user) {
        if ($user->wasChanged('title')) {
            // Title was changed and saved to DB
        }
        if ($user->isDirty('title')) {
            // Title was changed
        }
    });

Examining Attribute Changes

Upvotes: 1

matticustard
matticustard

Reputation: 5149

Yes, absolutely. You can use the Model class's existing methods to gain access to various sets of data. The following methods should be helpful for what you want to do.

getChanges()
Get the attributes that were changed. (and saved)

$model->getChanges()

getOriginal()
Get the model's original attribute values.

$model->getOriginal()

getDirty()
Get the attributes that have been changed since last sync. (but not saved yet)

$model->getDirty()

Upvotes: 13

Related Questions