Get previous attribute value in Eloquent model event

前端 未结 3 566
梦如初夏
梦如初夏 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: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.

提交回复
热议问题