Transferring intricate data from Blade to Vue layers

In my Laravel application, I have three models: Lesson, Quiz, and Answer (which should have been named Option). The relationships are set up so that each Lesson has Quizzes, and each Quiz has Answers. In a Blade file, I have access to a $lesson instance. My goal is to send both $lesson->quizzes and $quiz->answers from Blade to a VueJS method. Currently, I am only able to send the quizzes:

<modal-button color="success" size="small" icon="eye" header="View Quiz" btntxt="View Quiz" @showmodal="onShowViewQuizModal({{ $lesson->quizzes }})">
@include('partials.quizform')
</modal-button>

I receive the sent quizzes in my VueJS method and assign the array of objects to a VueJS data property:

onShowViewQuizModal(quizzes){
    this.quizzes = quizzes;
}

Within the quizform partial, I am attempting to display this nested data structure. My idea for accomplishing this is as follows:

<div v-for="quiz in quizzes">
    <p>@{{ quiz.title }}</p>

    <div v-for="answer in quiz.answers">
        <p>@{{ answer.title }}</p>
    </div>
</div>

Currently, only the outer v-for loop works, while the inner v-for loop does not because quiz.answers is likely undefined.

I hope you understand the issue, as it's common and many may have encountered it before. What would be the best way to handle this situation?

Answer №1

To establish a connection in your Quiz model, create the following relationship:

public function responses()
{
    return $this->hasMany('App\Answer'); // You can specify the foreign key as the second parameter
}

In your Laravel Controller method, use something similar to this:

return Quiz::with('responses')->get();

Your VueJS will handle everything else seamlessly.

Answer №2

It would be best to handle this before the view is displayed, but here's a possible solution.

<div v-for="quiz in quizzes">
    <p>@{{ quiz.title }}</p>
    <div v-if="quiz.answers">
      <div v-for="answer in quiz.answers">
          <p>@{{ answer.title }}</p>
      </div>
    </div>
</div>

If you need to add a property to an object that doesn't exist, you can try this approach.

for(x in quizzes){
  if(!x.hasOwnProperty('answers')){
    quizzes.x['answers] = []; <-- could use {} for object, depends what you're using for the answers when they exist
  }
}

Then update your code like so:

<div v-for="quiz in quizzes">
    <p>@{{ quiz.title }}</p>
    <div v-if="quiz.answers && quiz.answers.length > 0">
      <div v-for="answer in quiz.answers">
          <p>@{{ answer.title }}</p>
      </div>
    </div>
</div>

If answers is an object, you can check its length and constructor like this:

Object.keys(quiz.answers).length === 0 && quiz.answers.constructor === Object

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Boolean value retrieved from a NodeJS webservice behaves unexpectedly when incorporated into a test scenario

After calling a NodeJS webservice using the following code snippet: request({ url: "http://10.210.210.41:3001/trackable/lastPos", json: true }, function (error, response, body) { if (!error & ...

What is the best way to deactivate all active classes from buttons before selecting a new one?

I'm fairly new to working with Vue and I'm struggling to figure out how to properly handle buttons that need to have only one active at a time. Currently, I am using the activeBtn method but it doesn't seem to deactivate the previously activ ...

Sharing data with components via props

I have a question regarding the InputField.vue component. <template> <div class="w-full"> <label class="sr-only" :for="name"></label> <input :placeholder="label" :name="name" class="border-b border-bl ...

PHP/Laravel Method for Tracking Date Changes Every 24 Hours

I have a task where I need to generate a report that fetches data totals from a MySQL database and displays them in table rows. Each row should represent the totals for a 24-hour time frame (from 9 pm one day to 9 pm the next day). The timestamps in my dat ...

Locate an array within a Multidimensional array and relocate it to the starting position

I've been attempting to figure out a solution for moving a specific array within another array to the beginning. The problem I'm encountering is that the code I was using, as suggested in a previous question, only removes the last value and plac ...

Using Vue in an MVC architecture to display dynamic data sourced from a database

As I embark on my MVC project, I am eager to incorporate Vue.js into the front-end. How can I successfully bind my Vue script with the current model in order to retrieve data from the database? (Please note that I am still new to using Vue) (I have hear ...

Detecting Whether a Vue/Vue Router Navigation was Triggered by the Back/Forward Button or a Manual Router Push

When using vue/vue-router, I have set up a watcher on $route that is triggered in two different ways: By clicking back or forward on the browser. When the user interacts with a form. There are watchers on the variables that the form uses, and these watch ...

Is there a way to skip importing React from the test file when using Jest?

I'm currently using testing-library with React Within my test file, I have the following setup: import { render, screen } from '@testing-library/react' import React from 'react' // It would be ideal to avoid including this in each ...

What is causing the corruption of the .docx file returned by the Controller?

I am working on a .NET Core 2.2 web application. In one of my Controller methods, I perform editing tasks on a Word document and then send it back to the client. However, when I try to view the document on the client side, I encounter this dialog: https:/ ...

Sorting Json Data Using Vue

My experience with Vue.js led me to a challenge I can't quite figure out: how to filter specific data in a Json file. Let me provide more context: I have a Json file filled with various electronics products such as computers, mice, keyboards, etc. I w ...

The magic of handling buffers in NodeJS with JavaScript!

In my project, I am working on developing a client-server application. The goal is for the client to send a list of filenames to the server in an array format like this: let files = ["Cat.jpeg", "Moon.gif"]. To accomplish this task, I plan to utilize Buffe ...

I am looking for ways to identify the specific code responsible for causing a JavaScript heap out of memory issue

When I attempt to execute yarn start, I encounter the following error message: Starting the development server... ts-loader: Using [email protected] and C:\DevTools\git\mymoto\tsconfig.json <--- Last few GCs ---> [9076:000 ...

Managing the sequence of module loading in NodeJS

Consider this scenario: There are 3 files (modules) involved: app.js (async () => { await connectoDB(); let newRec = new userModel({ ...someprops }); await newRec.save(); })(); The app.ts serves as the entry point of the project. database ...

Having trouble with a blank page when starting up a basic Angular SPA in ASP .NET 5?

Currently, I am in the process of setting up a basic Angular single-page-application within ASP .NET 5. The project starts with a clean slate, with only the ngRoute Angular dependency included. The issue at hand: Upon running the project, I am faced wi ...

Insert mustache templates repetitively within a loop

I am having an issue with appending the same mustache template multiple times, each time with different values that are coming from PHP through AJAX. These values are stored in an array. The problem is that every time I append the template, it includes th ...

"Step-by-step guide on implementing a click event within a CellRenderer in Angular's Ag-Grid

paste your code hereI'm currently working on implementing edit and delete buttons within the same column for each row using Angular ag-Grid. To visually represent these buttons, I am utilizing icons. While I have successfully displayed the edit and de ...

Aligning my website in HTML

Is it possible for me to create a similar effect on my site like the one seen here ()? The site has a background with content layered on top of it. When you scroll the page horizontally, the content remains centered until you reach the very left edge, at w ...

Using the `useNavigate` function from React Router Dom may trigger a complete reload or re-render of the entire application, resulting

Whenever I attempt to programmatically navigate forward or back using a button click in React Router Dom, the useNavigate() function seems to clear all state, redux, and context and revert everything to its initial state. For example: <IconButton onCli ...

Iterating through elements within a Div will retrieve the initial element exclusively

Is there a way to loop through all elements within the MainDiv Div in order to retrieve their values? Currently, I am only able to retrieve the value of the first element. <div id="MainDiv"> <input type="text" id="MyText"value="Text1" /> ...

Guidelines for queuing method calls using Vue.js

Is there a way to invoke a method using a queue system? Imagine having a method that makes API calls and can only handle 3 calls at once. If more than 3 calls are made from a component, the remaining ones should wait until one call finishes before proceedi ...