84

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();
});
coatesap
  • 10,707
  • 5
  • 25
  • 33

3 Answers3

197

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.

coatesap
  • 10,707
  • 5
  • 25
  • 33
49

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

User::updating(function($user)
{
    if ($user->isDirty('username')){
        doSomething();
    }
});
Ola
  • 1,033
  • 9
  • 6
-5

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

Rob W
  • 9,134
  • 1
  • 30
  • 50