feat: register ActivityBuffer in AppServiceProvider to enhance activity logging capabilities

This commit is contained in:
Yoga Pangestu 2026-07-03 15:53:34 +07:00
parent 4ba6b9da9f
commit 59d7f94d0f
2 changed files with 47 additions and 1 deletions

View File

@ -11,6 +11,7 @@
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Spatie\Activitylog\Support\ActivityBuffer;
class AppServiceProvider extends ServiceProvider
{
@ -19,7 +20,10 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
//
$this->app->scoped(
ActivityBuffer::class,
\App\Support\ActivityLog\ActivityBuffer::class
);
}
/**

View File

@ -0,0 +1,42 @@
<?php
namespace App\Support\ActivityLog;
use Spatie\Activitylog\Support\ActivityBuffer as SpatieActivityBuffer;
use Spatie\Activitylog\Support\Config;
class ActivityBuffer extends SpatieActivityBuffer
{
public function flush(): void
{
if (empty($this->pending)) {
return;
}
$records = $this->pending;
// Collect all unique keys from all records
$allKeys = [];
foreach ($records as $record) {
foreach ($record as $key => $val) {
$allKeys[$key] = true;
}
}
// Normalize records so that every record has the exact same keys in the same order
$normalizedRecords = [];
foreach ($records as $record) {
$normalized = [];
foreach ($allKeys as $key => $_) {
$normalized[$key] = array_key_exists($key, $record) ? $record[$key] : null;
}
$normalizedRecords[] = $normalized;
}
$modelClass = Config::activityModel();
$modelClass::query()->insert($normalizedRecords);
$this->pending = [];
}
}