Search code examples
laravellaravel-8laravel-7laravel-auditing

Laravel Auditing update event not working


Laravel auditing on update does not work in my laravel eloquent application in few models. except for the user model. following is the audit.php events

'events' => [
    'created',
    'updated',
    'deleted',
    'restored',
],

 'strict' => false,
 'timestamps' => true,
 'console' => true,

I setup my model as follows

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;

use Illuminate\Support\Arr;

class Order extends Model implements Auditable
    use \OwenIt\Auditing\Auditable;
    use HasFactory;



    protected $fillable = [
        'order_date',              
        'cancel_date',             
        'comment',
        'remark',
        'customer_auto_id',       
        'customer',   
   ];             

    public function transformAudit(array $data): array
    {
        Arr::set($data, 'recode_auto_id',  $this->attributes['id']);

        return $data;
    }

    public function customer()
    {
        return $this->hasOne(User::class, 'id', 'customer_auto_id');
    }
}

creating and deleting works fine on audit except for update not auditing. please let me know the solvition.


Solution

  • I found the solution. on laravel, there can be two methods to update the recode

    method 01.

    $Object = Order::where('id', $order)
              ->update([
                        'name'=>$request->name,
                        'phone'=>$request->phone,
                      ]);
    

    Method 02.

    $Object           = Order::find($id);
    $Object ['name']  =  $request->name;
    $Object ['phone'] =  $request->phone;
    $Object ->save();
    

    at first, I have tried to audit the log using method 01. which doesn't log on update but created and deleted are logged. therefore I have tried method 02 which is logged created, updated, and deleted events successfully. I personally identified that method 02 can find the columns because it retrieves each column and then saves the changes so laravel may identify the changes for hit the log. use method 02 for solving the issue.

    $Object           = Order::find($id);
    $Object ['name']  =  $request->name;
    $Object ['phone'] =  $request->phone;
    $Object ->save();