I'm building an audit system in my application, and I want to compare an Eloquent Model attribute changes after save()
method. Here's an example of what I need:
$person = Person::find(1); //Original data: $person->name -> 'Original name', $person->age -> 22
$person->name = 'A new name';
$person->age = 23;
$person->save();
//At this point, I need to get an array like this (only with the attributes that have changed):
[
'age' => ['old' => 22, 'new' => 23],
'name' => ['old' => 'Original name', 'new' => 'A new name']
]
I know Eloquent already has some functions like isDirty()
, getDirty()
and getChanges()
, however this methods only return the new values, and I need to get the old and the new values to store in my audit table.
Is there any way to do this without need to "clone" my variables and then compare it to get the changes?