Computing Eloquent Model Deltas
Computing the differences or deltas between Eloquent models is a common
task in many data oriented apps. The easiest way that I have found out how to do so is below:
// This is assumed to be in \App\YourModel
/**
* @param \App\YourModel $model
*
* @return array
*/
public function delta(\App\YourModel $model)
{
// array_diff() is an easy way to produce deltas
$baseline = $model->attributesToArray();
$possiblyChanged = $this->attributesToArray();
/*
* $baseline = ['test' => 500, 'not_changed' => 5]
* $possiblyChanged = ['test' => 700, 'not_changed' => 5]
*/
/*
* $delta == ['test' => 700]
*/
$delta = array_diff($possiblyChanged, $baseline);
// Here I unset possible changes that I don't care about
unset($delta['id']);
unset($delta['created_at']);
unset($delta['updated_at']);
return $delta;
}