diff --git a/app/Http/Controllers/QuestionController.php b/app/Http/Controllers/QuestionController.php index 88acc2b..326e509 100644 --- a/app/Http/Controllers/QuestionController.php +++ b/app/Http/Controllers/QuestionController.php @@ -41,7 +41,48 @@ public function index(Request $request) }); } - return response()->json($query->get()); + return response()->json( + $query->get()->map(fn ($q) => $this->formatQuestion($q))->values() + ); + } + + /** + * Shape a question into the legacy (old Flutter) response: category_id and + * category are always present and non-null, tags is always an array, and + * timestamps are always ISO strings — so the old client never hits a null. + */ + private function formatQuestion(Question $question): array + { + $question->loadMissing(['tags', 'category']); + + $createdAt = optional($question->created_at)->toIso8601String(); + $updatedAt = optional($question->updated_at)->toIso8601String(); + $categoryId = $question->category_id ?? 0; + + $category = $question->category; + $categoryPayload = $category + ? [ + 'id' => $category->id, + 'name' => $category->name ?? '', + 'created_at' => optional($category->created_at)->toIso8601String() ?? $createdAt, + 'updated_at' => optional($category->updated_at)->toIso8601String() ?? $updatedAt, + ] + : [ + 'id' => $categoryId, + 'name' => '', + 'created_at' => $createdAt, + 'updated_at' => $updatedAt, + ]; + + return [ + 'id' => $question->id, + 'title' => $question->title ?? '', + 'category_id' => $categoryId, + 'created_at' => $createdAt, + 'updated_at' => $updatedAt, + 'tags' => $question->tags->values(), + 'category' => $categoryPayload, + ]; } /** @@ -75,7 +116,7 @@ public function store(Request $request) $question->tags()->sync($tagIds); } - return response()->json($question->load(['tags', 'category']), 201); + return response()->json($this->formatQuestion($question), 201); } /** @@ -83,7 +124,7 @@ public function store(Request $request) */ public function show(Question $question) { - return response()->json($question->load(['tags', 'category'])); + return response()->json($this->formatQuestion($question)); } /** @@ -120,7 +161,7 @@ public function update(Request $request, Question $question) $question->tags()->sync($tagIds); } - return response()->json($question->load(['tags', 'category'])); + return response()->json($this->formatQuestion($question->fresh())); } /**