Skip to content

Instantly share code, notes, and snippets.

@oddvalue
Created May 16, 2022 12:37
Show Gist options
  • Save oddvalue/1e50cc534b916515b8e006731cfe2825 to your computer and use it in GitHub Desktop.
Save oddvalue/1e50cc534b916515b8e006731cfe2825 to your computer and use it in GitHub Desktop.
Track previous attributes on a Laravel model

Lifted directly from @SteveTheBauman's tweet because I find myself needing this functionality very frequently https://twitter.com/SteveTheBauman/status/1524865758043553816

Example usage:

User.php

<?php
namespace App\Models;

use App\Concerns\TracksPreviousAttributes;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
  use TracksPreviousAttributes;
}
<?php
$user = User::create(['email' => '[email protected]']);
$user->update(['email' => '[email protected]']);

# ['email' => '[email protected]', ...]
$user->getPrevious();

# '[email protected]'
$user->getPrevious('email');
<?php
namespace App\Concerns;
use Illuminate\Database\Eloquent\Model;
trait TracksPreviousAttributes
{
protected $previous = [];
public static function bootTracksPreviousAttributes()
{
static::saving(function (Model $model) {
$model->previous = $model->getOriginal();
});
}
public function getPrevious(string $key = null)
{
if ($key !== null) {
return data_get($this->previous, $key);
}
return $this->previous;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment