Get previous attribute value in Eloquent model event

前端 未结 3 561
梦如初夏
梦如初夏 2020-12-23 09:09

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 p

相关标签:
3条回答
  • 2020-12-23 09:26

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

    0 讨论(0)
  • 2020-12-23 09:27

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

    User::updating(function($user)
    {
        if ($user->isDirty('username')){
            doSomething();
        }
    });
    
    0 讨论(0)
  • 2020-12-23 09:31

    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 carefult, it ignores the model type casting.

    0 讨论(0)
提交回复
热议问题