The results table store all the result of played quiz. it store id of user,question id and user choosen answer which may be correct or wrong.
answers table contain four answer with one correct option(is_correct) for particular question.
Now i want to find out how many answers were given correct and how many were given wrong.
in my controller
Result::where('quiz_id',$quizId)->where('user_id',$userId)->get();
in view
<?php $sum=0;?>
@foreach($results as $key =>$result)
<tr>
<td>{{$key+1}}</td>
<td>{{$result->question->name}}</td>
<td>{{$result->answer->answer}}</td>
@if($result->answer->is_correct==1)
<td>
<?php $sum = $sum+$key;
echo $sum;?>
Correct
</td>
@else
<td>Wrong</td>
@endif
i tried to count correct answer in view as well but i can't get the total correct answer given by user.
Any help is highly appreciated
Why are you using " + $key " ? Why not just " + 1 " ?
If you really get 1 or 0 back from your Model, you could even put your sum of correct answers outside of your if statement. If it is correct, you add 1, if not you add 0.
I also see you use $key for your first table cell, maybe you could change that and use the $loop variable available in blade loops. This way you can get rid of this $key completely.
Of course, you could also create another query in your Controller to find/count the correct answers. So you could get rid of your php calls in your blade views.