Search code examples
phparrayslaravellaravel-4laravel-3

Loop over an array of objects and get values in laravel PHP


I am working on a QA app where i need to add multiple answers to a question as per requirement dynamically. for this i am sending an object which carry question and the answers like.

question={
    'question_text':'what is your name',
    'answers':[
            {'answer_text':'some answer','isCorrect':'1'},
            {'answer_text':'some answer','isCorrect':'1'},
            {'answer_text':'some answer'}    // answer may or may not have isCorrect key
        ]
    }

On server side I have two tables or migrations 1 for Question and 1 for answer. The answer table have three fields question_id, answer_text' andisCorrect'. question_id is the foreign key of question in answer table.

to store the objects what i am doing is

$question_text=Input::get('question_text');
$answers=Input::get('answers');

$question=new Question;
$question->question_text=$question_text;
$question->save();


foreach($answers as $ans){ 
   $answer=new Answer;
   $answer->question_id=$question->id;
   $answer->answer_text=$ans->answer_text;
   if($answer->isCorrect){
        $answer->is_correct=$ans->isCorrect;
   }
   else{
        $answer->is_correct=0;
   }
   $answer->save();
}

But while iterating there is an error

`production.ERROR: exception 'ErrorException' with message 'Trying to get property of non-object'`  

what wrong I am doing here. I am first time working on PHP. I am trying to iterate it like Javascript or Python way. Tell me how can i get the values of answers array object and store them.


Solution

  • You dont seem to be referencing the array variables correctly. This should work:

    foreach($answers as $ans){ 
       $answer=new Answer;
       $answer->question_id=$question->id;
       $answer->answer_text=$ans['answer_text'];
       $answer->is_correct = isset($ans['isCorrect']);
       $answer->save();
    }
    

    p.s. Im not sure about forEach - I'm suprised it works - but you should probably rename it to foreach to confirm to the normal standards