CommentController.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Http\Controllers\Controller;
  4. use App\Http\Resources\CommentResource;
  5. use App\Models\Comment;
  6. use App\Models\Submission;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Http\JsonResponse;
  9. class CommentController extends Controller
  10. {
  11. // Список комментариев для заявки
  12. public function index(int $submissionId): JsonResponse
  13. {
  14. $submission = Submission::findOrFail($submissionId);
  15. $comments = $submission->comments()->with('attachments')->latest()->get();
  16. return response()->json([
  17. 'success' => true,
  18. 'data' => CommentResource::collection($comments),
  19. ]);
  20. }
  21. // Создание комментария
  22. public function store(Request $request, int $submissionId): JsonResponse
  23. {
  24. $submission = Submission::findOrFail($submissionId);
  25. $validated = $request->validate([
  26. 'author' => 'required|string|max:100',
  27. 'content' => 'required|string',
  28. ]);
  29. $comment = $submission->comments()->create($validated);
  30. $comment->load('attachments');
  31. return response()->json([
  32. 'success' => true,
  33. 'message' => 'Комментарий успешно добавлен',
  34. 'data' => new CommentResource($comment),
  35. ], 201);
  36. }
  37. // Обновление комментария
  38. public function update(Request $request, int $submissionId, int $id): JsonResponse
  39. {
  40. $comment = Comment::where('submission_id', $submissionId)->findOrFail($id);
  41. $validated = $request->validate([
  42. 'author' => 'sometimes|required|string|max:100',
  43. 'content' => 'sometimes|required|string',
  44. ]);
  45. $comment->update($validated);
  46. $comment->load('attachments');
  47. return response()->json([
  48. 'success' => true,
  49. 'message' => 'Комментарий успешно обновлен',
  50. 'data' => new CommentResource($comment),
  51. ]);
  52. }
  53. // Удаление комментария
  54. public function destroy(int $submissionId, int $id): JsonResponse
  55. {
  56. $comment = Comment::where('submission_id', $submissionId)->findOrFail($id);
  57. $comment->delete();
  58. return response()->json([
  59. 'success' => true,
  60. 'message' => 'Комментарий успешно удален',
  61. ]);
  62. }
  63. }