NotificationService.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Services;
  3. use App\Broadcasting\RealtimeEvent;
  4. use App\Broadcasting\RealtimeService;
  5. use App\Models\Notification;
  6. use Illuminate\Database\Eloquent\Collection;
  7. class NotificationService
  8. {
  9. public function __construct(
  10. private RealtimeService $realtime
  11. ) {}
  12. public function getByUser(int $userId): Collection
  13. {
  14. return Notification::where('user_id', $userId)
  15. ->orderBy('read', 'asc')
  16. ->orderBy('created_at', 'desc')
  17. ->get();
  18. }
  19. public function findById(int $id): Notification
  20. {
  21. return Notification::findOrFail($id);
  22. }
  23. public function create(array $data): Notification
  24. {
  25. return Notification::create($data);
  26. }
  27. public function delete(Notification $notification): void
  28. {
  29. $notification->delete();
  30. }
  31. //
  32. public function markAsRead(Notification $notification): Notification
  33. {
  34. $notification->update([
  35. 'read' => true,
  36. 'read_at' => now(),
  37. ]);
  38. return $notification;
  39. }
  40. public function markAllAsRead(int $userId): void
  41. {
  42. $updated = Notification::where('user_id', $userId)
  43. ->where('read', false)
  44. ->update([
  45. 'read' => true,
  46. 'read_at' => now(),
  47. ]);
  48. if ($updated === 0) {
  49. return;
  50. }
  51. $this->realtime->emitToUser(
  52. RealtimeEvent::NOTIFICATION_READ_ALL,
  53. $userId,
  54. ['entity' => 'notification', 'count' => $updated],
  55. );
  56. }
  57. public function unreadCount(int $userId): int
  58. {
  59. return Notification::where('user_id', $userId)
  60. ->where('read', false)
  61. ->count();
  62. }
  63. }