Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - insert multiple rows with pivot table data

I have 3 tables:

  1. Questions
  2. Answers
  3. question_answers

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:

enter image description here

I couldn't find a clue how to do it with the insert method

like image 362
TheUnreal Avatar asked Jun 09 '26 13:06

TheUnreal


1 Answers

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.

like image 172
Alexey Mezenin Avatar answered Jun 12 '26 10:06

Alexey Mezenin