Oops
Oops

Reputation: 1413

get $request inside loop. Laravel 5.8

I have multiple answer fields. First answer set is answer0 array second is answer1 array and so on. So I want to take like $request->answer0 , $request->answer1 this. I need this to be inside a for loop. I tried something like this but failed to get the answer.

for ($i = 0; $i < count($arry); $i++) {
    $qstn = new SurveyQuestions();
    $qstn->question_name = $arry[$i][0];
    $qstn->survey_id = $request->survey_id;
    $qstn->survey_group_id = $groupId;
    $qstn->answer_datatype_id = $arry[$i][1];
    $qstn->question_image_path = $qstnfileNames;
    $qstn->save();

    $qstnId = $qstn->id;

    for ($j = 0; $j < count($request->answer . $j); $j++) {
        $ans = new SurveyQuestionAnswers();
        $ans->survey_question_id = $qstnId;
        $ans->answer = $request->answer1[$j];
        $ans->save();
    }
}

but this gives me error

Count(): Parameter must be an array or an object that implements countable.

echo '<pre>'; print_r($request->answer); // gives me "1"

if I get like this ( $request->answer0 ), I will be able to save answer arrays of particular question id to database.

dd($request->all())

array:9 [▼
   "group_name" => "Group 1"
   "survey_id" => "5"
   "question_name" => array:2 [▼
     0 => "q1"
     1 => "q2"
     ]
  "answer_datatype_id" => array:2 [▶]
  "answer1" => array:2 [▼
     0 => "aa"
     1 => "bb"
     ]
  "answer2" => array:2 [▼
     0 => "cc"
     1 => "dd"
     ]
  "group_image_path" => UploadedFile {#394 ▶}
  "question_image_path" => array:2 [▶]
  ]

From the above output, I need id of q1 and its corresponding answer1 array to be saved in database. Then with id of q2 and answer2 array to be inserted in database and so on. Thanks in advance.

Upvotes: 1

Views: 559

Answers (2)

madalinivascu
madalinivascu

Reputation: 32354

You need to loop over the questions like this:

foreach($request->question_name as $i =>$name)
$qstn = new SurveyQuestions(); 
$qstn->question_name = $name;
$qstn->survey_id = $request->survey_id;
$qstn->survey_group_id = $groupId;
$qstn->answer_datatype_id = $request->answer_datatype_id[$i] 
$qstn->question_image_path =$this->question_image_path[$i];
$qstn->save();

$qstnId = $qstn->id; 

$name = "answer".$i;
foreach($request->{$name} as $value)
    $ans = new SurveyQuestionAnswers();
    $ans->survey_question_id = $qstnId;
    $ans->answer = $value;
    $ans->save();
}

Upvotes: 2

Jesus Erwin Suarez
Jesus Erwin Suarez

Reputation: 1585

The request should show like this

$request->answer[0] not $request->answer0

so in your blade or view you should make it like so

<input name="answer[]" />

in your controller do this

for($j=0;$j<count($request->answer); $j++){
    $ans = new SurveyQuestionAnswers();
    $ans->survey_question_id = $qstnId;
    $ans->answer = $request->answer[$j];
    $ans->save();
    }
  }

Upvotes: 0

Related Questions