Travel back in time to see past model states, and restore them in one line.
use App\Models\Article;
$article = Article::find(1);
$article->rewind()->toLatest();
Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can spread the word!
Call Composer to retrieve the package.
composer require laragear/rewind
First, install the migration file. This migration will create a table to save all previous states from your models.
php artisan vendor:publish --provider="Laragear\Rewind\RewindServiceProvider" --tag="migrations"
Tip
You can edit the migration by adding new columns before migrating, and also change the table name.
php artisan migrate
Finally, add the HasRewind
trait into your models you want its state to be saved when created and updated.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Laragear\Rewind\HasRewind;
class Article extends Model
{
use HasRewind;
// ...
}
That's it. Next time you want restore the previous state of a model, use the rewind()
method.
use App\Models\Article;
$article = Article::find(1);
$article->rewind()->toLatest();
When your model is created, and subsequently updated, a new state is saved into the database. That state in comprised of the raw attributes of your original model.
With the rewind()
helper method, you can easily peek and restore a previous model states like the last one, or have a list of states ready to be restored from. Additionally, the HasRewind
trait allows to control when to save states, and what to save and restore.
States are reactive, not proactive. In other words, states are saved after the original model is saved, not before.
States are created automatically when the model is created or updated. There is nothing you need to do to ensure the state has been persisted, but you can hear for the StatePushed
event.
use App\Models\Article;
use Illuminate\Http\Request;
public function store(Request $request)
{
$validated = $request->validate([
// ...
]);
return Article::create($validated); // First state created automatically.
}
public function update(Article $article, Request $request)
{
$validated = $request->validate([
// ...
]);
$article->update($validated); // State pushed automatically.
return $article;
}
Sometimes you will want to avoid creating a replica when a model is created or updated.
To do that, use the withoutCreatingStates()
method of your model with a callback. Inside the callback, the states won't be pushed to the database.
use App\Models\Article;
use Illuminate\Http\Request;
public function store(Request $request)
{
$validated = $request->validate([
// ...
]);
// Create an article but don't save the first state.
return Article::withoutCreatingStates(fn() => Article::create($validated));
}
If you have disabled automatic states creation, then you may save a state manually using the create()
method.
use App\Models\Article;
use Illuminate\Http\Request;
public function store(Request $request)
{
$validated = $request->validate([
// ...
]);
$article = Article::create($validated);
$article->rewind()->create(); // Save the first state.
return $article;
}
public function update(Article $article, Request $request)
{
$validated = $request->validate([
// ...
]);
$article->update($validated);
$article->rewind()->create(); // Push a new state.
return $article;
}
The create()
method allows keep the state from automatic pruning, and also skip automatic pruning.
$article->rewind()->create(
keep: true,
prune: false,
);
If you want, you can save a state without updating the original model. For example, you can create a bunch of articles "drafts".
public function draft(Article $article, Request $request)
{
$validated = $request->validate([
// ...
]);
// Push a state from the updated article without persisting it.
$article->fill($validated)->rewind()->create();
return back();
}
To get a list of all prior models states use the all()
method. It will return an Eloquent Collection of all past models.
use App\Models\Article;
$pastArticles = Article::find(1)->rewind()->all();
Tip
You can use the state ID to later restore a given state ID.
To count all the saved states, use the count()
method. It will return the number of persisted states.
use App\Models\Article;
$count = Article::find(1)->rewind()->count();
To avoid counting all the states and only check if there is at least one state made for the model, use the exists()
method.
use App\Models\Article;
$hasAtLeastOneState = Article::find(1)->rewind()->exists();
Alternatively, the missing()
method checks if there are no states saved for the model.
use App\Models\Article;
$hasNoStates = Article::find(1)->rewind()->missing();
You may also use findLatest()
and findOldest()
if you need to find the first or the last model state, respectively.
use App\Models\Article;
$latest = Article::find(1)->rewind()->getLatest();
$oldest = Article::find(1)->rewind()->getOldest();
To retrieve a model instance by its state ID, use the find()
method.
use App\Models\Article;
$pastArticle = Article::find(1)->rewind()->find(456);
Caution
Because the State ID is expected to exist, a ModelNotFoundException
will be thrown if id doesn't exist.
The easiest way to restore a prior state data into the same model instance is using the to()
method with the ID of the state to restore, and just calling save()
to persist the changes in the database.
use App\Models\Article;
$article = Article::find(1);
$article->title; // "Happy cavations!"
$article->rewind()->to(468)->save();
$article->title; // "Happy vacations!"
Alternatively, you can always restore the model to the latest or oldest state using toLatest()
or toOldest()
, respectively.
use App\Models\Article;
Article::find(1)->rewind()->toLatest()->save();
Article::find(1)->rewind()->toOldest()->save();
Important
When the model restored is updated, it will create a new state. To avoid this, use withoutCreatingStates()
.
If you retrieve prior model state, you will virtually have two instances in your code: the current one, and the past state model.
Saving the past state will replace the data of the original in the database. The original instance will not be aware of the changes made, so you should refresh the model, or discard it.
use App\Models\Article;
$stale = Article::find(1);
$stale->title; // "Happy vatacions!"
$past = $original->rewind()->getLatest();
$past->save();
$stale->title; // "Happy vatacions!"
$stale->fresh()->title; // "Happy vacations!"
You may delete a state the delete()
and the ID of the state.
use App\Models\Article;
Article::find(1)->rewind()->remove(765);
You may also use the deleteLatest()
or deleteOldest()
to delete the latest or oldest state, respectively.
use App\Models\Article;
$article = Article::find(1);
$article->rewind()->removeLatest();
$article->rewind()->removeOldest();
Important
Using deleteLatest()
and deleteOldest()
do not delete kept states, you will need to issue true
to force its deletion.
Article::find(3)->rewind()->deleteOldest(true);
You may call the clear()
method to delete all the states from a model.
use App\Models\Article;
Article::find(1)->rewind()->clear();
Since this won't include kept states, you can use forceClear()
to include them.
use App\Models\Article;
Article::find(1)->rewind()->forceClear();
Every time the model is updated, it automatically prunes old model states to keep a limited number of states. If you have disabled it, you may need to call the prune()
method manually to remove stale states.
use App\Models\Article;
Article::find(1)->rewind()->prune();
Note
When retrieving states, states to-be-pruned are automatically left out from the query.
This package fires the following events:
Event name | Trigger |
---|---|
StateRestored | At developer discretion |
StateDeleted | Fires when a state is deleted from the database |
StatePushed | Fires when a state is pushed to the database |
StatesCleared | Fires when states are cleared from the database |
StatesPruned | Fires when states are pruned from the database |
For example, you can listen to the StatePushed
event in your application with a Listener.
use Laragear\Rewind\Events\StateCreated;
class MyListener
{
public function handle(StateCreated $event)
{
$event->model; // The target model.
$event->state; // The RewindState Model with the data.
}
}
The StateRestored
event is included for convenience. If you decide to restore a model to a previous state, you may trigger it using StateRestored::dispatch()
manually with the model instance.
use App\Models\Article;
use Illuminate\Support\Facades\Route;
use Laragear\Rewind\Events\StateRestored;
Route::post('article/{article}/restore', function (Article $article) {
$article->rewind()->toOldest()->save();
StateRestored::dispatch($article);
return back();
});
Model States data are saved into the Laragear\Rewind\Models\RewindState
model. This model is mostly responsable for creating a new model instance from the raw data it holds.
Use the query()
method to start a query for the given model. You may use this, for example, to paginate results.
use App\Models\Article;
$page = Article::find(1)->rewind()->query()->paginate();
You may also use the model instance query directly for further custom queries.
use Laragear\Rewind\Models\RewindState;
RewindState::query()->where('created_at', '<', now()->subMonth())->delete();
Sometimes you will want to change how the rewind procedure works on your model. You can configure when and how states are saved using the trait methods.
By default, the limit of rewind states is 10, regardless of how old these are. You may change the amount by returning an integer in the rewindLimit()
method.
public function rewindLimit()
{
return 10;
}
You may also change the limit to a moment in time. States created before the given moment won't be considered on queries and will be pruned automatically when saving a model.
public function rewindLimit()
{
return now()->subMonth();
}
To limit by both an amount and a date at the same time, return an array with both.
public function rewindLimit()
{
return [10, now()->subMonth()];
}
Finally, you may disable limits by returning falsy, which will ensure all states are saved.
public function rewindLimit()
{
return false;
}
Every time you create or update a model, a new state is created in the database. You may change this behaviour using shouldCreateRewindStateOnCreated()
and shouldCreateRewindStateOnUpdated()
, respectively.
public function shouldCreateRewindStateOnCreated(): bool
{
// Don't save states if the article body is below a certain threshold.
return strlen($this->body) < 500;
}
public function shouldCreateRewindStateOnUpdated(): bool
{
// Only let subscribed users to have states saved.
return $this->user->hasSubscription();
}
This may be useful if you want to not save a model state, for example, if an Article doesn't have enough characters in its body, or if the User is not subscribed to a plan.
By default, everytime a new state is pushed into the database, it prunes the old states. You may disable this programmatically using shouldPruneOldRewindStatesOnUpdated()
.
public function shouldPruneOldRewindStatesOnUpdated(): bool
{
return true;
}
When you create a model, the initial state can be lost after pushing subsequent new states. To avoid this, you can always protect the first state, or any state, with shouldKeepFirstRewindState()
.
public function shouldKeepFirstRewindState(): bool
{
return true;
}
Tip
If the first state is protected, it won't be pruned, so only newer states will rotate.
By default, all raw attributes of the model are added into the state data. You can override this by setting your own attributes to use in the state to save by returning an associative array or an \Illuminate\Contracts\Support\Arrayable
instance.
use Illuminate\Contracts\Support\Arrayable;
public function getAttributesForRewindState(): Arrayable|array
{
return [
'author_id' => $this->author_id,
'title' => $this->title,
'slug' => $this->slug,
'body' => $this->body,
'private_notes' => null,
'published_at' => $this->published_at,
];
}
To modify how the model should be filled with the attributes from the state, use the setAttributesFromRewindState()
. It receives the raw attributes from the state as an array.
use Illuminate\Support\Arr;
public function setAttributesFromRewindState(array $attributes): void
{
$this->setRawAttributes(Arr::except($attributes, 'excerpt'));
}
- There are no singletons using a stale application instance.
- There are no singletons using a stale config instance.
- There are no singletons using a stale request instance.
- There are no static properties written on every request.
There should be no problems using this package with Laravel Octane.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
This specific package version is licensed under the terms of the MIT License, at time of publishing.
Laravel is a Trademark of Taylor Otwell. Copyright © 2011-2024 Laravel LLC.