HistoryTracker

Codacy BadgeStyleCILicenseTotal DownloadsLatest Stable Version

Simple to use, customizable Laravel Model history tracking utility trait

Details

The trait helps keep track of the changes made to a model by saving a snapshot for each relevant update of the model to a different 'history' table.

The records in the history table are linked via FK to the original model. Setting a FK constraint on the DB column may be set if necessary.

Usage

You can choose the attributes you want to track from the model by declaring them as fillable in the history model.

When the model is created an initial snapshot of the desired attributes is saved. When the model is updated, if any one of the tracked attributes has changed, a new snapshot/history entry is persisted.

  1. Create a histories table, such as model_histories - where model is what you need to keep track of.

  2. Create a corresponding history model, such as ModelHistory and add as fillable the attributes you want tracked:

protected $fillable = ['tracked', 'attributes', 'list'];

WARNING

Don't forget to also have the FK column for the relationship to the tracked model.

  1. Use the trait in the tracked model:
use HistoryTracker;
  1. Add the $historyModel property to the tracked model:
protected $historyModel = ModelHistory::class;

The trait also defines a relationship to the history model instances, so you can access the snapshots by calling histories:

$myModel->histories;

Notes

Laravel Enso already included and ready to use out of the box. The package itself has no other dependencies beyond Laravel.

Last Updated: 7/23/2018, 4:47:10 AM