Steve Steve - 6 months ago 11
PHP Question

Retreiving an array name

I have used array name in form. this routes to the controller function shown below.

<form method="POST" action="{{url('quiz/check')}}"
{!! csrf_field() !!}

@foreach ($quiz as $q)

@if($q->level=='1')
{{ $q->qid }}.
{{ $q->question }}<br>
<input type='radio' name='mycheck[{{$q->qid}}]' value='1'>
{{ $q->opt1 }}<br>
<input type='radio' name='mycheck[{{$q->qid}}]' value='2'>
{{ $q->opt2 }}<br>
<input type='radio' name='mycheck[{{$q->qid}}]' value='3'>
{{ $q->opt3 }}<br>
<input type='radio' name='mycheck[{{$q->qid}}]' value='4'>
{{ $q->opt4 }}<br><br>
@endif
@endforeach
<button type="submit" class="btn btn-default">Get result</button>
</form>


which i am trying to retrieve in controller as:

public function check(Request $request)
{
$count=0;
$input=$request->all();
$mycheck=$input['mycheck'];
$ch = DB::select('select * from quiz where category="gk" ');
return View('quiz.check',['quiz'=>$ch,'input'=>$input,'count'=>$count]);
}


view file
check.blade.php


Results:
@foreach ($quiz as $q)

@if(array_key_exists($q->qid, $mycheck) && $mycheck[$q->qid]==$q->answer)
{{$count=$count+1}}

@endif

@endforeach

You scored {{$count}}.


now, i am getting this error:


undefined variable: mycheck in view file

Answer

You are not passing $mycheck variable to view.

Replace this line:

return View('quiz.check',['quiz'=>$ch,'input'=>$input,'count'=>$count]);     

With this:

return View('quiz.check',['quiz'=>$ch,'input'=>$input,'count'=>$count,'mycheck'=>$mycheck]);   

Also, looks like You trying to access variable $q which is actually variable $quiz according to Your data passed to view.