I have 3 tables:
Question Model:
public function answer()
{
return $this->belongsToMany(Answer::class);
}
I created a page where I type a question and 4 answers, and I insert them to my database.
$question = new Question;
$question->title = $request->question_title;
$question->save();
$answers = $request->answers;
$answer = Answer::insert($answers);
How I can insert the question_answers for each question too?
question_answers looks like this:

I couldn't find a clue how to do it with the insert method
Since you're using many-to-many relationship, you should use attach() method. For example:
$question = Question::create($request->question); // Save question.
$answersIds = [];
foreach ($request->answers as $answer) {
$answersIds [] = Answer::create($answer)->id; // Save each answer.
}
$question->answers()->attach($answersIds); // Attach answers to the question.
Also you can't use insert() to bulk insert answers, because you need to get answer IDs to attach answers to the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With