Hey Jacob,
I've justed tested your plugin and really like it.
Maybe its an idea to make this a reportwidget as well for all models? In this way you can have some kind of revision log. Maybe we can even add an undo button, because we store the changes in the database anway.
Already tried this quick-and-dirty in your plugin:
public function boot() {
// Extend all (!) models
Model::extend(function($model) {
// Prevent errors and looping
if(!empty($model->table) && $model->table != 'jacob_logbook_logs') {
$user = BackendAuth::getUser();
if (!$user) {
$backendUserId = null;
} else {
$backendUserId = $user->getKey();
}
// Create
$model->bindEvent('model.afterCreate', function() use ($model, $backendUserId) {
$changes = new Changes([
'type' => Changes::TYPE_CREATED,
]);
Log::create([
'model' => get_class($model),
'model_key' => $model->getKey(),
'changes' => $changes->getData(),
'backend_user_id' => $backendUserId,
]);
});
// Update
$model->bindEvent('model.afterUpdate', function() use ($model, $backendUserId) {
$attributes = [];
$dirtyAttributes = $model->getDirty();
$originalAttributes = $model->getOriginal();
$ignoreFieldsLogbook = ['updated_at'];
foreach($dirtyAttributes as $column => $newValue)
{
if(in_array($column, $ignoreFieldsLogbook))
{
continue;
}
$attributeChanged = new Attribute([
'column' => $column,
'column_name' => $model->getField($column),
'old' => $originalAttributes[$column] ?? null,
'new' => $newValue,
]);
$attributes[] = $attributeChanged->getData();
}
$changes = new Changes([
'type' => Changes::TYPE_UPDATED,
'changedAttributes' => $attributes
]);
Log::create([
'model' => get_class($model),
'model_key' => $model->getKey(),
'changes' => $changes->getData(),
'backend_user_id' => $backendUserId,
]);
});
// Delete
$model->bindEvent('model.afterDelete', function() use ($model, $backendUserId) {
$changes = new Changes([
'type' => Changes::TYPE_DELETED,
]);
Log::create([
'model' => get_class($model),
'model_key' => $model->getKey(),
'changes' => $changes->getData(),
'backend_user_id' => $backendUserId,
]);
});
}
});
}
Unfortunately I couldn't find a way to extend the models with the existing LogChanges trait. Something like this would be better ofcourse (maybe something for October to implement in its core):
Model::extend(function($model) {
if(!empty($model->table) && $model->table != 'jacob_logbook_logs') {
$model->implement[] = Log::class;
// Or: $model->addTrait(Log::class);
}
}
After extending the models I've made a reportwidget. Almost the same as the formwidget, which results in the log showing on the dashboard:

What do you think?