LoginSignup
0
2

Laravel Auditingのログがクエリビルダのイベントでは記録されない

Last updated at Posted at 2024-04-16

概要

業務でLaravel Auditingを使用しており、監視対象のカラムが変更された際にレコードがInsertされない事象に対応したときの備忘録です。
間違いがあればご指摘をいただけると嬉しいです!

Laravel Auditingとは

Laravel Auditingとは、DBにおいてレコードに変更が行われた際、自動でログを記録してくれるパッケージのこと。
どのカラムが誰によってどんな風に変更されたか監視することができます。
(問い合わせサポート業務とかであると助かるかも…)

クエリビルダを使用した場合はテーブルにレコードが入らない

以下のドキュメントにもあるようにクエリビルダによるDBの更新は記録されません。
EloquentでModelを使って変更してあげる必要があります。
https://laravel-auditing.com/guide/community/troubleshooting.html
https://laravel-auditing.com/guide/community/why-laravel-auditing.html

Eloquentを使用しよう

Auditingで記録したいならEloquentを使用しましょう!

サンプル

Modelクラス

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AuditTarget extend Model implements Auditable
{
    use \OwenIt\Auditing\Auditable;

    private $table = 'audit_target';

    /**
     * Attributes to include in the Audit.
     * ここでは監視対象を指定します
     * デフォルトは全カラムが対象
     * @var array
     */
    protected $auditInclude = [
        'audit_target',
    ];

    /**
     * Attributes to exclude from the Audit.
     * ここでは監視から除外するカラムを指定できます
     * デフォルトは除外カラムの指定はありません
     * @var array
     */
    protected $auditExclude = [
        'excludion_target',
    ];
}

変更処理(create・delete・update・save)

これでOK


namespace App\Service;

use App\Models\AuditTarget;

class Service
{
    public function update()
    {
        $changeTarget = AuditTarget::first();
        $changeTarget->update([
            'column' => 'hoge',
        ]);
    }
}

最後に

そもそもイントロダクションに書いてありました…
(公式ドキュメントはちゃんと読もう!)

This powerful tool offers detailed auditing capabilities for Eloquent models, allowing you to keep track of changes made to records, as well as any changes to their attributes.

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2