NotificationService.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Notification;
  4. use Illuminate\Database\Eloquent\Collection;
  5. class NotificationService
  6. {
  7. public function getByUser(int $userId): Collection
  8. {
  9. return Notification::where('user_id', $userId)
  10. ->orderBy('read', 'asc')
  11. ->orderBy('created_at', 'desc')
  12. ->get();
  13. }
  14. public function findById(int $id): Notification
  15. {
  16. return Notification::findOrFail($id);
  17. }
  18. public function create(array $data): Notification
  19. {
  20. return Notification::create($data);
  21. }
  22. public function markAsRead(Notification $notification): Notification
  23. {
  24. $notification->update([
  25. 'read' => true,
  26. 'read_at' => now(),
  27. ]);
  28. return $notification;
  29. }
  30. public function markAllAsRead(int $userId): void
  31. {
  32. Notification::where('user_id', $userId)
  33. ->where('read', false)
  34. ->update([
  35. 'read' => true,
  36. 'read_at' => now(),
  37. ]);
  38. }
  39. public function unreadCount(int $userId): int
  40. {
  41. return Notification::where('user_id', $userId)
  42. ->where('read', false)
  43. ->count();
  44. }
  45. public function delete(Notification $notification): void
  46. {
  47. $notification->delete();
  48. }
  49. }