Files
eCert-MBIP/src/app/Services/AuditLogService.php

40 lines
1.2 KiB
PHP

<?php
namespace App\Services;
use App\Models\AuditLog;
use Illuminate\Database\Eloquent\Model;
class AuditLogService
{
public static function log(
string $action,
?Model $model = null,
array $oldValues = [],
array $newValues = []
): void {
try {
AuditLog::create([
'user_id' => auth()->id(),
'action' => $action,
'auditable_type' => $model ? get_class($model) : null,
'auditable_id' => $model?->getKey(),
'old_values' => self::redact($oldValues),
'new_values' => self::redact($newValues),
'ip_address' => request()->ip(),
'user_agent' => substr(request()->userAgent() ?? '', 0, 500),
]);
} catch (\Throwable) {
// Audit log failure must not break the main flow.
}
}
private static function redact(array $values): array
{
// Never log these sensitive fields.
$sensitive = ['no_kp', 'password', 'token', 'remember_token'];
return array_diff_key($values, array_flip($sensitive));
}
}