| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- namespace App\Services;
- use App\Broadcasting\RealtimeEvent;
- use App\Broadcasting\RealtimeService;
- use App\Models\Notification;
- use Illuminate\Database\Eloquent\Collection;
- class NotificationService
- {
- public function __construct(
- private RealtimeService $realtime
- ) {}
- public function getByUser(int $userId): Collection
- {
- return Notification::where('user_id', $userId)
- ->orderBy('read', 'asc')
- ->orderBy('created_at', 'desc')
- ->get();
- }
- public function findById(int $id): Notification
- {
- return Notification::findOrFail($id);
- }
- public function create(array $data): Notification
- {
- return Notification::create($data);
- }
- public function delete(Notification $notification): void
- {
- $notification->delete();
- }
- //
- public function markAsRead(Notification $notification): Notification
- {
- $notification->update([
- 'read' => true,
- 'read_at' => now(),
- ]);
- return $notification;
- }
- public function markAllAsRead(int $userId): void
- {
- $updated = Notification::where('user_id', $userId)
- ->where('read', false)
- ->update([
- 'read' => true,
- 'read_at' => now(),
- ]);
- if ($updated === 0) {
- return;
- }
- $this->realtime->emitToUser(
- RealtimeEvent::NOTIFICATION_READ_ALL,
- $userId,
- ['entity' => 'notification', 'count' => $updated],
- );
- }
- public function unreadCount(int $userId): int
- {
- return Notification::where('user_id', $userId)
- ->where('read', false)
- ->count();
- }
- }
|