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

tanmay_das's avatar

Displaying recursive model data with vuejs in laravel

I have 3 models: Lesson, Quiz and Answer. Lesson hasMany() Quizzes, Quiz hasMany() Answers. To view the quiz and each answer associated with the quiz, in my blade template I was doing something like this:

@foreach ($lesson->quizzes as $quiz)
    <p>{{ $quiz->title }}</p>
    @foreach ($quiz->answers as $answer)
    <div class="field">
        <control>
            <inp type="radio" @optionselected="onRadioChanged" name="{{ 'answer'.$answer->quiz_id }}" val="{{ $answer->id }}">{{ $answer->title }}</inp>
        </control>
    </div>
    @endforeach
    <hr>
@endforeach

It works fine. But the problem is it populates the modal with all of the quizzes, like this: https://imgur.com/jmOL1vl

But I want only one quiz at a time and I would like to show the next quiz when the user clicks the Next button. And to do that, I guess I need the help of Vue. So I ended up doing something like this:

@foreach ($lesson->quizzes as $quiz)
    <p>{{ $quiz->title }}</p>
    <div class="field" v-for="answer in answers">
        <control>
            <inp type="radio" @optionselected="onRadioChanged" name="answer.quiz_id" val="answer.id">@{{ answer.title }}</inp>
        </control>
    </div>
    <hr>
@endforeach 

I am passing $lesson->quizzes as the argument of the vue method onShowViewQuizModal(quizzes) to fetch the answers forEach() of the quizzes with an ajax call:

data: { answers: [] },
methods:{
    onShowViewQuizModal: function(quizzes){
          var that = this;
        quizzes.forEach(function(quiz){
          axios.post('/fetchanswers', {quizid: quiz.id}).then(function(response){
            that.answers = response.data;
            console.log(that.answers);
          });

        });

        this.showViewQuizModal = true;
      } 
}

And the route method which is responding to this ajax call:

Route::post('/fetchanswers',function(){
    $quiz = Quiz::find(request('quizid'));
    return $quiz->answers;
});

But now, In my view, my modal is being populated with the last answer only: https://imgur.com/MmHGe2Q How can I fix this?

0 likes
0 replies

Please or to participate in this conversation.