History - Laravel
In Laravel, the History
trait allows you to keep track of a model's changes by recording them in a separate History model. In this article, we'll explore how to use the History
trait, its syntax, and its benefits.
Syntax
First, you need to add a history()
method to your model. This method returns a morphMany relationship to the History
model.
use Plank\Mediable\Mediable;
class Image extends Model
{
use Mediable, \Spatie\Activitylog\Traits\LogsActivity;
protected static $logAttributes = ['name', 'description'];
public function history()
{
return $this->morphMany(History::class, 'model');
}
// More methods...
}
Then, you need to add the LogsActivity
trait to your model and define which attributes you want to log using the $logAttributes
property.
use Plank\Mediable\Mediable;
class Image extends Model
{
use Mediable, \Spatie\Activitylog\Traits\LogsActivity;
protected static $logAttributes = ['name', 'description'];
public function history()
{
return $this->morphMany(History::class, 'model');
}
// More methods...
}
Example
$image = Image::find(1);
$image->name = 'New name';
$image->description = 'New description';
$image->save();
This code updates an existing Image
model's name
and description
attributes. The History
trait records these changes in the history
table.
Output
When the Image
model is saved, a new row is added to the history
table.
id | model_type | model_id | description | created_at | updated_at |
---|---|---|---|---|---|
1 | App\Image | 1 | name changed from Old name to New name |
2021-07-01 12:00:00 | 2021-07-01 12:00:00 |
2 | App\Image | 1 | description changed from Old description to New description |
2021-07-01 12:00:00 | 2021-07-01 12:00:00 |
Explanation
The History
trait uses the morphMany
relationship to associate a model with its history records. When the model is saved, the trait records any changes made to it in the history
table.
Use
The History
trait is useful when you need to keep track of changes made to a model. This can be helpful for auditing, debugging, and troubleshooting purposes.
Important Points
- The
History
trait uses themorphMany
relationship to associate a model with its history records. - The
$logAttributes
property can be used to define which model attributes should be logged. - The
History
is useful for auditing, debugging, and troubleshooting purposes.
Summary
The History
trait is a powerful feature in Laravel that allows you to keep track of a model's changes by recording them in a separate history table. By using the History
trait, developers can create more robust and maintainable applications.