ChatGPT解决这个技术问题 Extra ChatGPT

Get previous attribute value in Eloquent model event

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

c
coatesap

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.


getOriginal has one parameter which is the name of the field you looking for.
Do you know if that returns the previous object or it returns the first value ever?
be carefult, it ignores the model type casting.
Do note that ever since Laravel 7.x, this method has been renamed to getRawOriginal(). See upgrade guide: laravel.com/docs/7.x/upgrade
@RobinvanBaalen - I haven't tested it, but the new behaviour of getOriginal since Laravel 7 actually seems more desirable for doing these comparisons, as I expect the current attribute value has already had casting applied...
O
Ola

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

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

Works in 5.2.39 too. Thanks Ola.
This doesn't get the previous value
R
Rob W

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


and now we can do it right here class AppServiceProvider extends ServiceProvider in boot method.