NotificationService.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 delete(Notification $notification): void
  23. {
  24. $notification->delete();
  25. }
  26. //
  27. public function markAsRead(Notification $notification): Notification
  28. {
  29. $notification->update([
  30. 'read' => true,
  31. 'read_at' => now(),
  32. ]);
  33. return $notification;
  34. }
  35. public function markAllAsRead(int $userId): void
  36. {
  37. Notification::where('user_id', $userId)
  38. ->where('read', false)
  39. ->update([
  40. 'read' => true,
  41. 'read_at' => now(),
  42. ]);
  43. }
  44. public function unreadCount(int $userId): int
  45. {
  46. return Notification::where('user_id', $userId)
  47. ->where('read', false)
  48. ->count();
  49. }
  50. }