diff --git a/app/Http/Controllers/QuestionController.php b/app/Http/Controllers/QuestionController.php index 5971a76..9c68666 100644 --- a/app/Http/Controllers/QuestionController.php +++ b/app/Http/Controllers/QuestionController.php @@ -27,6 +27,13 @@ public function create() public function store(Request $request) { + $question = Question::create($request->only('title', 'description')); + foreach ($request->input('answers')??[] as $newAnswer) { + $answer = $question->answers()->updateOrCreate(['id' => $newAnswer['id'] ?? null], ['text' => $newAnswer['text']]); + $answer->attributes()->sync(collect($newAnswer['attributes'])->pluck('id')); + } + + return to_route('questions.index')->with('success', 'Question saved!'); } public function edit($id) @@ -41,12 +48,12 @@ public function update(Request $request, $id) { $question = Question::findOrFail($id); $question->update($request->only('text', 'description')); - foreach ($request->input('answers') as $newAnswer) { + foreach ($request->input('answers')??[] as $newAnswer) { $answer = $question->answers()->updateOrCreate(['id' => $newAnswer['id'] ?? null], ['text' => $newAnswer['text']]); $answer->attributes()->sync(collect($newAnswer['attributes'])->pluck('id')); } - return to_route('questions.edit', $question->id)->with('success', 'Question saved!'); + return to_route('questions.index')->with('success', 'Question saved!'); } public function destroy($id)