createdBy = $createdBy ?? Auth::id(); } /** * Get the notification's delivery channels. * * @return array */ public function via(object $notifiable): array { // Manually save to our custom notifications table here $this->saveToCustomDatabase($notifiable); return []; } /** * Save to the custom notifications table. */ protected function saveToCustomDatabase(object $notifiable): void { // Prevent duplicate entries for the same system notification within a short window. // This is necessary because system notifications are often sent to multiple users // (e.g., all Administrators), but we only want one entry in the global log. $recent = NotificationModel::where('title', $this->title) ->where('message', $this->message) ->where('recipient', $this->recipient) ->where('created_at', '>=', now()->subSeconds(5)) ->exists(); if ($recent) { return; } $notification = NotificationModel::create([ 'title' => $this->title, 'message' => $this->message, 'type' => $this->type, 'recipient' => $this->recipient, 'created_by' => $this->createdBy, ]); // Broadcast a NotificationSent event so the UI updates in real-time. // We do this here once after the database record is created. event(new NotificationSent($notification)); } }