devitek/eloquent-loggable

让您的 eloquent 模型可记录日志

0.1.1 2016-08-20 20:19 UTC

This package is auto-updated.

Last update: 2024-09-24 01:36:02 UTC


README

SensioLabsInsight Latest Stable Version Total Downloads Latest Unstable Version License

此包提供了一种简单的方法来让您的 Eloquent 模型可记录日志。它的工作方式类似于 Gedmo/Loggable 扩展对 doctrine。

安装

运行

composer require devitek/eloquent-loggable

config/app.php 中添加服务提供者

'providers' => [
    // Other Service Providers

    Devitek\Laravel\Eloquent\Loggable\EloquentLoggableServiceProvider::class,
],

获取迁移

php artisan vendor:publish --provider="Devitek\Laravel\Eloquent\Loggable\EloquentLoggableServiceProvider" --tag="migrations"

然后运行

php artisan migrate

如何使用它

在您的 Eloquent 模型中添加

<?php

use \Devitek\Laravel\Eloquent\Loggable;

class MyModel extends Model
{
    use Loggable;

    protected $versioned = [
        'name',
        'other_field',
        'another_field',
        'again_another_field',
    ];
    
    protected $reason = 'my_reason_field';
}

现在,每次您持久化模型时,所有在 versioned 属性中声明的字段都会被检查(如果已更改)并记录。

原因属性表示哪个字段将用于日志消息。这不是必需的,默认情况下,日志消息将为空。在持久化之前,此字段将被清除,这样您就可以使用动态字段。

获取日志条目

现在,您的模型上有一个方法:logEntries,这是一个 morphTo 关系。

$logEntries = $model->logEntries();

foreach ($logEntries as $logEntry) {
    /**
     * LogEntry object :
     * action, logged_at, object_id, version, reason, data (as json), user_id
     */
}

回滚

您可以使用 revert 方法回滚模型到之前的状态,如下所示

$model = MyModel::find($id);

$model->revert(); // Revert to the first revision
$model->revert(5); // Revert to the 5th revision

享受它!请随意分叉 :) !