NotificationController.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Requests\NotificationRequest;
  4. use App\Http\Resources\NotificationResource;
  5. use App\Http\Resources\NotificationSendResource;
  6. use App\Services\NotificationService;
  7. use Illuminate\Http\JsonResponse;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Support\Facades\Auth;
  10. class NotificationController extends Controller
  11. {
  12. public function __construct(protected NotificationService $service) {}
  13. public function index(): JsonResponse
  14. {
  15. $items = $this->service->getAll();
  16. return $this->successResponse(payload: NotificationResource::collection($items));
  17. }
  18. public function indexPaginated(Request $request): JsonResponse
  19. {
  20. $perPage = min((int) $request->get('per_page', 12), 100);
  21. $paginator = $this->service->getAllPaginated($perPage);
  22. return $this->successResponse(payload: [
  23. 'data' => NotificationResource::collection($paginator->items()),
  24. 'total' => $paginator->total(),
  25. 'from' => $paginator->firstItem() ?? 0,
  26. 'to' => $paginator->lastItem() ?? 0,
  27. ]);
  28. }
  29. public function store(NotificationRequest $request): JsonResponse
  30. {
  31. $item = $this->service->create($request->validated());
  32. return $this->successResponse(
  33. payload: new NotificationResource($item),
  34. message: __('messages.created'),
  35. code: 201,
  36. );
  37. }
  38. public function show(int $id): JsonResponse
  39. {
  40. $item = $this->service->findById($id);
  41. return $this->successResponse(payload: new NotificationResource($item));
  42. }
  43. public function destroy(int $id): JsonResponse
  44. {
  45. $this->service->delete($id);
  46. return $this->successResponse(message: __('messages.deleted'), code: 204);
  47. }
  48. public function myUnread(): JsonResponse
  49. {
  50. $items = $this->service->getUnreadByUser(Auth::id());
  51. return $this->successResponse(payload: NotificationSendResource::collection($items));
  52. }
  53. public function myNotifications(): JsonResponse
  54. {
  55. $items = $this->service->getByUser(Auth::id());
  56. return $this->successResponse(
  57. payload: NotificationSendResource::collection($items)
  58. );
  59. }
  60. public function markAsRead(int $sendId): JsonResponse
  61. {
  62. $this->service->markAsRead($sendId, Auth::id());
  63. return $this->successResponse(message: __('messages.updated'));
  64. }
  65. }