Reputation: 7022
I have several answers for a question. My question input filed is like below.
<input name="question" type="text" class="form-control" placeholder="Place your question here">
I am adding multiple answers dynamically. My answer input field is like below.
<input name="answer[]" type="text" class="form-control" placeholder="Place your answer here">
I made question Table using these columns 'id','question','created_at','updated_at'.
I made answer Table using these columns 'id','question_id','answer','created_at','updated_at'.
I am using below code to save Question and Answers.
public function add_form(Request $request)
{
$question = Question::create(['question' => request()->input('question')]);
$question->answers()->create([request()->input('answer')]);
}
I am getting below error.
SQLSTATE[HY000]: General error: 1364 Field 'answer' doesn't have a default value (SQL: insert into `answers` (`question_id`, `updated_at`, `created_at`) values (4, 2021-08-05 11:56:16, 2021-08-05 11:56:16))
Upvotes: 0
Views: 29
Reputation: 15319
First map single dimension array to multidimensional array.
$answer=collect(request()->answer)->transform(function ($item){
return ['answer'=>$item];
})->toArray();
and while saving
$question->answers()->createMany($answer);
Upvotes: 1