NotificationController.php 1.9 KB

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