NotificationObserver.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace App\Observers;
  3. use App\Broadcasting\RealtimeEvent;
  4. use App\Broadcasting\RealtimeService;
  5. use App\Models\Notification;
  6. class NotificationObserver
  7. {
  8. public function __construct(
  9. private RealtimeService $realtime
  10. ) {}
  11. public function created(Notification $notification): void
  12. {
  13. $this->realtime->emitToUser(
  14. RealtimeEvent::NOTIFICATION_CREATED,
  15. $notification->user_id,
  16. [
  17. 'entity' => 'notification',
  18. 'id' => $notification->id,
  19. 'type' => $notification->type,
  20. ],
  21. );
  22. }
  23. public function updated(Notification $notification): void
  24. {
  25. if (! $notification->wasChanged('read') || ! $notification->read) {
  26. return;
  27. }
  28. $this->realtime->emitToUser(
  29. RealtimeEvent::NOTIFICATION_READ,
  30. $notification->user_id,
  31. [
  32. 'entity' => 'notification',
  33. 'id' => $notification->id,
  34. ],
  35. );
  36. }
  37. }