Ryan R
Ryan R

Reputation: 23

Laravel saving question_id from question table in choices table with belongsTo relation

I am doing question and answer form. I have 2 tables questions table and choices table. I am perfectly saving the question data and choices data to their table except the question_id in choices table. I want to save the question id to choices table field name question_id.

question table

| id | question |
|  1 | data1    |
|  2 | data2    |

choices table

| id | question_id | choices |
|  1 |             | data1   |
|  2 |             | data2   |

Below is my controller

        $questions = $request->question;
        foreach($questions as $question => $question_value) {

            $questionsS[] = Question::create([
                'question' => $request->question[$question],
            ]);
        }


        $choices = $request->choices;
        foreach ($choices as $choice => $choice_value) {
            $choicesS[] = Choice::create([
                'question_id' => $question->id,
                'choice' => $choice_value,
            ]);
        }

I have error "Attempt to read property "id" on int" highlighting the 'question_id' => $question->id,

Hope someone help.

Upvotes: 0

Views: 40

Answers (1)

Desod
Desod

Reputation: 1

simplely,

  • The last time of first loop, you can see $question variable is index of the loop.
  • You should merge two foreach loop to do right action.

i dont know your goal, but if i fix it, your code should be like:

    $questions = $request->question;
    // may be ['question one ?', 'question two ?' ...]
    $choices = $request->choices;
    // may be ['choose A', 'choose B' ...]
    // $questions array and $choices array must be same length
    // i think in your case it will be same length, right ?
    foreach($questions as $questionIndex => $question) {
        $currentQuestion = Question::create([
            'question' => $question,
        ]);
        $questionsS[] = $currentQuestion;
        $choicesS[] = Choice::create([
            'question_id' => $currentQuestion->id,
            'choice' => $choices[$questionIndex],
        ]);
    }

$currentQuestion in loop will be an object which created from array's element, you can get id from it to create an new Choice object.

Upvotes: 0

Related Questions