Get previous attribute value in Eloquent model event

PhpLaravelLaravel 4Eloquent

Php Problem Overview


Is there a way to see the old/previous value of a model's attribute in its saving or updating event?

eg. Is something like the following possible:

User::updating(function($user)
{
    if ($user->username != $user->old->username) doSomething();
});

Php Solutions


Solution 1 - Php

Ok, I found this quite by chance, as it's not in the documentation at present...

There is a getOriginal() method available which returns an array of the original attribute values:

User::updating(function($user)
{
    if ($user->username != $user->getOriginal('username')) {
        doSomething();
    }

    // If you need multiple attributes you may use:
    // $originalAttributes = $user->getOriginal();
    // $originalUsername = $originalAttributes['username']; 
});

> Be careful, prior to Laravel 7 getOriginal ignores attribute type casting.

Solution 2 - Php

In Laravel 4.0 and 4.1, you can check with isDirty() method:

User::updating(function($user)
{
    if ($user->isDirty('username')){
        doSomething();
    }
});

Solution 3 - Php

You could overload the methods, then call the parent method.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncoatesapView Question on Stackoverflow
Solution 1 - PhpcoatesapView Answer on Stackoverflow
Solution 2 - PhpOlaView Answer on Stackoverflow
Solution 3 - PhpRob WView Answer on Stackoverflow