Now that GPT can summarize logs, let’s take it further by using it to automatically detect suspicious behavior, such as:
- Excessive deletions
- Unusual access times
- Repeated updates to sensitive models
This helps prevent abuse or unauthorized activities in your Laravel system.
🛡 Step 1: Extend your helper for anomaly detection
Update AuditSummaryHelper.php
with a new method:
public static function detectAnomalies(array $logs): string
{
$entries = collect($logs)->map(function ($log) {
return "- {$log->created_at->format('Y-m-d H:i')} | " .
(optional($log->causer)->name ?? 'System') . " | {$log->description}";
})->implode("\n");
$prompt = <<<PROMPT
You are a Laravel audit analyst. Analyze the following activity logs and list any anomalies, suspicious patterns, or unusual behaviors. Mention users, times, and actions.
$entries
Anomalies:
PROMPT;
$response = OpenAI::chat()->create([
'model' => 'gpt-4o',
'messages' => [
['role' => 'user', 'content' => $prompt],
],
'max_tokens' => 400,
]);
return $response->choices[0]->message->content ?? 'No anomalies detected.';
}
📡 Step 2: Add a route and controller for anomaly detection
In web.php
:
Route::post('/audit-logs/analyze', [\App\Http\Controllers\AuditLogController::class, 'analyze'])->name('audit.logs.analyze');
In AuditLogController.php
:
public function analyze(Request $request)
{
$logs = Activity::with('causer')->latest()->take(30)->get();
$anomalies = AuditSummaryHelper::detectAnomalies($logs);
return back()->with('anomalies', $anomalies);
}
🧪 Step 3: Add “Detect Anomalies” button to view
In index.blade.php
:
<form method="POST" action="{{ route('audit.logs.analyze') }}" class="mb-4 inline-block">
@csrf
<button class="bg-red-500 text-white px-3 py-1 rounded">Detect Anomalies</button>
</form>
🧾 Step 4: Show the GPT-detected anomalies
Still in index.blade.php
, above the table:
@if(session('anomalies'))
<div class="bg-red-100 text-red-800 p-3 rounded mb-4">
<strong>GPT Detected Anomalies:</strong><br>
{!! nl2br(e(session('anomalies'))) !!}
</div>
@endif
🧠 Example Output
GPT Detected Anomalies:
- Jane Doe deleted 12 records between 2:00–2:05 AM, which is outside normal working hours.
- User “admin” updated the same customer record 6 times in 10 minutes.
- System user performed a data deletion without an associated login.
✅ Tomorrow (Day 5), we’ll group activity by user roles and departments, then use GPT to explain team-based actions in plain English.