NotificationController.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\Notification;
  4. use App\Services\NotificationService;
  5. use Carbon\Carbon;
  6. use Illuminate\Http\JsonResponse;
  7. use Illuminate\Support\Facades\Auth;
  8. class NotificationController extends Controller
  9. {
  10. public function __construct(
  11. private NotificationService $service
  12. ) {}
  13. public function index(): JsonResponse
  14. {
  15. $user = Auth::user();
  16. $notifications = Notification::where('user_id', $user->id)
  17. ->orderBy('read', 'asc')
  18. ->orderBy('created_at', 'desc')
  19. ->limit(50)
  20. ->get()
  21. ->map(function ($notification) {
  22. return [
  23. 'id' => $notification->id,
  24. 'title' => $notification->title,
  25. 'description' => $notification->description,
  26. 'origin' => $notification->origin,
  27. 'origin_id' => $notification->origin_id,
  28. 'type' => $notification->type,
  29. 'read' => $notification->read,
  30. 'time' => Carbon::parse($notification->created_at)->diffForHumans(),
  31. ];
  32. });
  33. return $this->successResponse(
  34. payload: $notifications
  35. );
  36. }
  37. public function markAsRead(int $id): JsonResponse
  38. {
  39. $notification = Notification::where('id', $id)
  40. ->where('user_id', Auth::id())
  41. ->firstOrFail();
  42. $notification->update([
  43. 'read' => true,
  44. 'read_at' => now(),
  45. ]);
  46. return $this->successResponse(
  47. message: __('messages.updated')
  48. );
  49. }
  50. public function markAllAsRead(): JsonResponse
  51. {
  52. $this->service->markAllAsRead(Auth::id());
  53. return $this->successResponse(
  54. message: __('messages.updated')
  55. );
  56. }
  57. }