Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

david001's avatar

How to query this

Hi in my app

results table

i have id/user_id/question_id/quiz_id/answer_id

in questions table id/quiz_id/name

in answers table id/question_id/answer/is_correct

quiz table id/name

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
0 likes
2 replies
itsfg's avatar

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.

itsfg's avatar

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.

And by the way, in your blade views, instead of

<?php
...
?>

you can use

@php
...
@endphp
1 like

Please or to participate in this conversation.