owen-it / laravel-auditing

Record the change log from models in Laravel
https://laravel-auditing.com
MIT License
3.05k stars 390 forks source link

Audit is not created when manually triggering the updated event on model #878

Closed omerbaskurt closed 11 months ago

omerbaskurt commented 11 months ago
Q A
Bug? yes
New Feature? no yes
Framework Laravel
Framework version 10.23.1
Package version 13.5.1
PHP version 8.2.12

I update a property of a model and saveQuietly to not to trigger events on the save. Then, manually fire the update event later. I expect an update audit getting triggered but it doesn't. created, restored, deleted events work as expected.

$article->title = $newTitle;
$article->saveQuietly();
...
event('eloquent.updated: App\Models\Article', $article);

updated is included in the audit config file (audit.php)

'events' => [
        'created',
        'updated',
        'deleted',
        'restored'
],
parallels999 commented 11 months ago

Maybe it's because update uses dirty, and after saving, dirty is empty Try this way

$article->title = $newTitle;
event('eloquent.updated: App\Models\Article', $article);
$article->saveQuietly();
omerbaskurt commented 11 months ago

Thanks, that does the trick. But it kinda defeats the purpose of not firing events on save. We do fire the events after the business logic block. Something like this:

$article->title = $newTitle;
$article->saveQuietly();
$events[] = ['updated', 'App\Models\Article', $article];

$user->restoreQuietly();
$events[] = ['restored', 'App\Models\User', $user];

... a bunch of other operations without events while saving event data

// then fire the events
foreach ($events as $event) {
    event('eloquent.' . $event[0] . ': ' . $event[1], $event[2]);
}
parallels999 commented 11 months ago

Did you try clone before save??

$article->title = $newTitle;
$events[] = ['updated', 'App\Models\Article', clone $article];
$article->saveQuietly();

I can't give you a specific answer if you don't specify the full scenario

omerbaskurt commented 11 months ago

Using clone on the event works, thank you.