esign/laravel-database-auditing 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

esign/laravel-database-auditing

Composer 安装命令:

composer require esign/laravel-database-auditing

包简介

Track database changes in Laravel using database triggers.

README 文档

README

Latest Version on Packagist Total Downloads GitHub Actions

This package allows you to track changes in your database using database triggers. Currently only MySQL is supported.

Note This package is designed to track database changes that occur outside of Laravel. However, for changes originating within a Laravel application, other solutions like owen-it/laravel-auditing may better suit your requirements.

Installation

You can install the package via composer:

composer require esign/laravel-database-auditing

The package will automatically register a service provider.

This package comes with a migration to store your database changes. You can publish the migration file:

php artisan vendor:publish --provider="Esign\DatabaseAuditing\DatabaseAuditingServiceProvider" --tag="migrations"

Running this command will publish the following migration:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('audits', function (Blueprint $table) {
            $table->id();
            $table->string('event');
            $table->morphs('auditable');
            $table->json('old_data')->nullable();
            $table->json('new_data')->nullable();
            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('audits');
    }
};

Next up, you can optionally publish the configuration file:

php artisan vendor:publish --provider="Esign\DatabaseAuditing\DatabaseAuditingServiceProvider" --tag="config"

The config file will be published as config/database-auditing.php with the following contents:

return [
    /**
     * Specifies the model used by the package to retrieve audits.
     */
    'model' => Esign\DatabaseAuditing\Models\Audit::class,
];

Usage

Creating database triggers

To track database changes, use the php artisan make:audit-trigger command. This will generate a migration file with the necessary trigger configuration:

use Esign\DatabaseTrigger\DatabaseTrigger;
use Esign\DatabaseTrigger\Enums\TriggerEvent;
use Esign\DatabaseTrigger\Enums\TriggerTiming;
use Esign\DatabaseTrigger\Facades\Schema;
use Illuminate\Database\Migrations\Migration;

return new class extends Migration
{
    public function up(): void
    {
        Schema::createTrigger('audit_after_posts_insert', function (DatabaseTrigger $trigger) {
            $trigger->on('posts');
            $trigger->timing(TriggerTiming::AFTER);
            $trigger->event(TriggerEvent::INSERT);
            $trigger->statement("
                insert into audits (
                    event,
                    auditable_type,
                    auditable_id,
                    old_data,
                    new_data
                ) values (
                    'insert',
                    'post',
                    NEW.id,
                    NULL,
                    JSON_OBJECT('title', NEW.title, 'slug', NEW.slug)
                );
            ");
        });
    }

    public function down(): void
    {
        Schema::dropTriggerIfExists('audit_after_posts_insert');
    }
};

By default, a trigger name will be automatically assigned based on the provided input. However, you can specify a different name by passing it as the first argument:

php artisan make:audit-trigger my_trigger

Retrieving tracked changes

After running the trigger migration, any modifications made to the associated table will be automatically monitored and stored in the audits table.

Here is a representation of how audits are stored in the audits table based on different trigger events:

id event auditable_type auditable_id old_data new_data
1 insert post 1 NULL {"title": "My Post"}
2 update post 1 {"title": "My Post"} {"title": "My Updated Post"}
3 delete post 1 {"title": "My Post"} NULL

To retrieve the recorded changes in your Laravel project, you can utilize the Esign\DatabaseAuditing\Models\Audit model provided by the package. Here's an example:

use Esign\DatabaseAuditing\Models\Audit;

$audits = Audit::query()->get();

To determine if any data changes occurred in an audit, you can utilize the hasDataChanges() method available on the Audit model. Here's how you can use it:

use Esign\DatabaseAuditing\Models\Audit;

$latestAudit = Audit::latest()->first();
$latestAudit->hasDataChanges();
$latestAudit->hasDataChanges('slug');

The hasDataChanges() method returns a boolean value indicating whether any changes were made. If you pass a specific attribute name as an argument, it will check for changes in that particular attribute only.

To retrieve audits based on specific trigger events, you can use the event() scope provided by the Audit model. Here's an example:

use Esign\DatabaseAuditing\Models\Audit;
use Esign\DatabaseTrigger\Enums\TriggerEvent;

Audit::event(TriggerEvent::UPDATE)->first();

Tracking changes in Eloquent models

To track changes related to your Eloquent model, apply the Esign\DatabaseAuditing\Concerns\HasAudits trait to the respective model. For instance:

use Esign\DatabaseAuditing\Concerns\HasAudits;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasAudits;
}

This will enable an audits relationship on the model, allowing you to access the tracked changes. For example:

$post = Post::first();
$latestAudit = $post->audits()->latest()->first();

Feel free to explore the Esign\DatabaseAuditing\Models\Audit model for more functionality related to tracking and retrieving changes.

Testing

composer test

License

The MIT License (MIT). Please see License File for more information.

esign/laravel-database-auditing 适用场景与选型建议

esign/laravel-database-auditing 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 24 次下载、GitHub Stars 达 0, 最近一次更新时间为 2023 年 07 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「esign」 「database-auditing」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 esign/laravel-database-auditing 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 esign/laravel-database-auditing 我们能提供哪些服务?
定制开发 / 二次开发

基于 esign/laravel-database-auditing 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 24
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 15
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-07-10