了解谁在您的 Laravel 应用中操作了您的模型。

v1.0.9 2023-04-08 06:57 UTC

This package is auto-updated.

Last update: 2024-09-23 15:51:15 UTC


README

Package Logo

Latest Stable Version Total Downloads License

hexadog/laravel-auditable 帮助您自动注册对您的模型执行操作的用戶。

安装

此包需要 PHP 7.3 和 Laravel 7.0 或更高版本。

要开始使用,请使用 Composer 安装 Auditable

composer require hexadog/laravel-auditable

该包将自动注册其服务提供者。

使用方法

将新的 auditable 宏添加到您的迁移中。

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('posts', function (Blueprint $table) {
    $table->auditable();
});

Schema::table('posts', function (Blueprint $table) {
    $table->dropAuditable();
});

它将添加以下列

  • created_at
  • created_by
  • updated_at
  • updated_by
  • deleted_at
  • deleted_by

注意:您无需使用 timestamps()softDeletes() 宏。Auditable 宏将为您集成它们。

如果您修改了数据库并希望删除可审计列,可以使用宏 $table->dropAuditable();

一旦数据库迁移完成,您可以在您的模型中使用 Auditable 特性。

use Hexadog\Auditable\Models\Traits\Auditable;

class Post extends Models
{
    use Auditable;

    // ...
}

这样,每次数据被修改时,负责该操作的用户 ID(创建、更新、软删除)都会自动注册到模型的相关列中。您无需做任何事情。

检索操作负责的用户

您可以通过调用特性提供的辅助方法之一来检索执行最后操作的用戶(创建、更新、删除)。

要确定模型创建的用戶,您可以使用 created_by 属性来获取 ID 或 createdBy 关系来获取目标模型

// Get user responsible of the creation of the post
$post->createdBy;

// Get the creation date
$post->created_at;

要确定模型最后更新的用戶,您可以使用 updated_by 属性来获取 ID 或 updatedBy 关系来获取目标模型

// Get user responsible of the last update of the post
$post->updatedBy;

// Get the last update date
$post->updated_at;

要确定模型删除的用戶(仅当模型使用 SoftDeletes 特性时),您可以使用 deleted_by 属性来获取 ID 或 deletedBy 关系来获取目标模型

// Get user responsible of the post deletion (ONLY if soft deletes are used)
$post->deletedBy;

// Get the soft deletion date
$post->deleted_at;

致谢

许可协议

Laravel Auditable 是开源软件,受 MIT 许可协议 许可。