在Laravel中,创建一个日志来存储资源的所有更改


In Laravel, create a log to store all changes of resources

在我的Laravel应用程序中,我想创建一个审计日志,它基本上是一个针对许多"资源"(客户端、帐户等)的CRUD应用程序。这将使我能够看到应用程序中任何资源的任何创建、删除或编辑,何时发生,以及是哪个用户进行了更改。

我首先创建了以下模式(以及相关的模型Change):

Schema::create('changes', function(Blueprint $table)
{
    $table->increments('id');
    $table->dateTime('change_date')->nullable(); //The time the change was made
    $table->string('model'); // The model the change was made to
    $table->text('change'); // What was changed (e.g. `name` field for client 10015 was changed from "John" to "Johnny")
    $table->integer('user_id')->unsigned()->nullable(); // The user who made the change
    $table->timestamps();
});

现在,每当对另一个模型进行更改时,我都希望我的应用程序在更改表中插入一条记录。例如,假设客户端被编辑,则需要在Client->save()之后运行一些额外的代码。类似于:

$change = new Change;
$change->user_id = User()->id;
$change->model = // ? how do I get the name of the model just changed?
$change->change = 'User 10015 edited: name: "John" -> "Johnny"; active: 1 -> 0;'; // somehow get the fields that were changed. Different for delete and create.
$change->save();

我想我需要制作3个过滤器(或者事件监听器?),每个过滤器用于创建、编辑和删除。但是,我如何传入所需的数据(如字段和模型名称)?有没有一个包已经做到了这一点?感谢您的帮助。

编辑这个可修改的包似乎完成了我想要的95%——只是不记录创建和删除。

您可以添加一个事件侦听器并激发一个事件。您可以在start.php文件中注册事件,也可以创建events.php文件并要求在start.php文件中注册。您也可以使用服务提供商和类来完成此操作。

示例:

Event::listen('user.change', function($param1, $param2, $optional = null) {
    // insert a change record here
});

每当你需要添加更改时,你只需执行以下操作:

Event::fire('user.change', ['parameter 1', 'parameter 2']);

显然,您可以根据需要更改硬编码参数。