Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Eloquent log record before and after changing it

I have a simple question, whenever I use Eloquent to edit a record in the DB, I'd like to be able to log the values of this row before and after the save.

My solution so far:

  • I have a parent model class that extends Eloquent: App\Models\Model.php
  • Then all my other models extend this Model.php, so inside this file, I'm overriding eloquent save() method.

But by the time, the save method is called, the eloquent builder object has new values, the old ones have been overwritten.

Any ideas on how to do this ?

like image 643
Alucard Avatar asked Feb 03 '26 02:02

Alucard


1 Answers

You can use the model events for this, there are many events like saving, updating, deleting ... for more details look here

class SomeModel extends Eloquent {

  protected static function boot()
  {
    parent::boot();  // don't forget to call the parent boot method
    //On saving
    static::saving(
      function($record)
      {
        $dirty = $record->getDirty();
        foreach ($dirty as $field => $newdata)
        {
          $olddata = $record->getOriginal($field);
          if ($olddata != $newdata)
          {
            // Do what it takes here :)
          }
        }
        return true;
      }
    );
  }
}
like image 63
Maraboc Avatar answered Feb 05 '26 23:02

Maraboc