PM_Console/backend/app/Http/Controllers/Api/NotificationController.php

111 خطوط
3.8 KiB
PHP

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\NotificationResource;
use App\Models\Notification;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class NotificationController extends Controller
{
public function index(Request $request): JsonResponse
{
try {
$query = $request->user()->notifications();
$perPage = $request->input('per_page', 15);
$notifications = $query->orderBy('created_at', 'desc')->paginate($perPage);
return response()->json([
'success' => true,
'data' => NotificationResource::collection($notifications),
'meta' => [
'current_page' => $notifications->currentPage(),
'last_page' => $notifications->lastPage(),
'per_page' => $notifications->perPage(),
'total' => $notifications->total(),
'unread_count' => $request->user()->notifications()->whereNull('read_at')->count(),
],
'message' => 'لیست اعلان‌ها',
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'خطا در دریافت اعلان‌ها',
], 500);
}
}
public function markAsRead(Notification $notification): JsonResponse
{
try {
if ($notification->user_id !== request()->user()->id) {
return response()->json([
'success' => false,
'message' => 'شما اجازه دسترسی به این اعلان را ندارید',
], 403);
}
$notification->update(['read_at' => Carbon::now(), 'is_read' => true]);
return response()->json([
'success' => true,
'data' => new NotificationResource($notification->fresh()),
'message' => 'اعلان به عنوان خوانده شده علامت خورد',
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'خطا در به‌روزرسانی اعلان',
], 500);
}
}
public function markAllAsRead(Request $request): JsonResponse
{
try {
$request->user()->notifications()->whereNull('read_at')->update([
'read_at' => Carbon::now(),
'is_read' => true,
]);
return response()->json([
'success' => true,
'message' => 'همه اعلان‌ها به عنوان خوانده شده علامت خوردند',
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'خطا در به‌روزرسانی اعلان‌ها',
], 500);
}
}
public function destroy(Request $request, Notification $notification): JsonResponse
{
try {
if ($notification->user_id !== $request->user()->id) {
return response()->json([
'success' => false,
'message' => 'شما اجازه حذف این اعلان را ندارید',
], 403);
}
$notification->delete();
return response()->json([
'success' => true,
'message' => 'اعلان حذف شد',
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'خطا در حذف اعلان',
], 500);
}
}
}