store/app/Services/System/NotificationService.php

70 lines
1.7 KiB
PHP

<?php
namespace App\Services\System;
use App\Models\Notification;
use App\Models\User;
class NotificationService
{
public function listForUser(User $user): array
{
$notifications = Notification::query()
->where('user_id', $user->id)
->latest()
->limit(20)
->get()
->map(fn (Notification $notification) => [
'id' => $notification->id,
'title' => $notification->title,
'body' => $notification->body,
'url' => $notification->url,
'is_read' => $notification->is_read,
'created_at' => $notification->created_at->toIso8601String(),
]);
$unreadCount = Notification::query()
->where('user_id', $user->id)
->unread()
->count();
return [
'notifications' => $notifications,
'unread_count' => $unreadCount,
];
}
public function markAsRead(Notification $notification, User $user): void
{
if ($notification->user_id !== $user->id) {
abort(403);
}
$notification->markAsRead();
}
public function markAllAsRead(User $user): void
{
Notification::query()
->where('user_id', $user->id)
->unread()
->update(['is_read' => true, 'read_at' => now()]);
}
public function delete(Notification $notification, User $user): void
{
if ($notification->user_id !== $user->id) {
abort(403);
}
$notification->delete();
}
public function deleteAll(User $user): void
{
Notification::query()
->where('user_id', $user->id)
->delete();
}
}