2👍
✅
Define a relationship in your Quiz model like this:
public function answers()
{
return $this->hasMany('App\Answer'); // second parameter can be used to define foreign key
}
In your Laravel Controller method do something like:
return Quiz::with('answers')->get();
Your VueJS will take care off the rest.
0👍
I’d aim to take care of that before the view is rendered… But this might do it.
<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>
To add a property to an object where is doesn’t exist you could do something like this
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
}
}
and then…
<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>
That’s for arrays, now if answers
is an object, you could use
Object.keys(quiz.answers).length === 0 && quiz.answers.constructor === Object
Source:stackexchange.com