store/app/Http/Controllers/Admin/NotificationController.php

82 lines
2.1 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Notification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class NotificationController extends Controller
{
public function index(Request $request): JsonResponse
{
$user = $request->user();
$notifications = Notification::query()
->where('user_id', $user->id)
->latest()
->limit(20)
->get()
->map(fn (Notification $n) => [
'id' => $n->id,
'title' => $n->title,
'body' => $n->body,
'url' => $n->url,
'is_read' => $n->is_read,
'created_at' => $n->created_at->toIso8601String(),
]);
$unreadCount = Notification::query()
->where('user_id', $user->id)
->unread()
->count();
return response()->json([
'notifications' => $notifications,
'unread_count' => $unreadCount,
]);
}
public function markAsRead(Request $request, Notification $notification): JsonResponse
{
if ($notification->user_id !== $request->user()->id) {
abort(403);
}
$notification->markAsRead();
return response()->json(['success' => true]);
}
public function markAllAsRead(Request $request): JsonResponse
{
Notification::query()
->where('user_id', $request->user()->id)
->unread()
->update(['is_read' => true, 'read_at' => now()]);
return response()->json(['success' => true]);
}
public function destroy(Request $request, Notification $notification): JsonResponse
{
if ($notification->user_id !== $request->user()->id) {
abort(403);
}
$notification->delete();
return response()->json(['success' => true]);
}
public function destroyAll(Request $request): JsonResponse
{
Notification::query()
->where('user_id', $request->user()->id)
->delete();
return response()->json(['success' => true]);
}
}