Skip to content
Advertisement

how to retrieve data from laravel relationship?

Hello im trying to do a quiz app with laravel and im struggeling with retrieving my questions with category..

i have a unsightly solution with this but it’s not dynamically..

JavaScript

i thought i could to that with the relationship like $question->category->id but wont work.

thats my model:

JavaScript

i cant somehow pass the id and check it i dont know why.. thats my form where i pass the category:

JavaScript

Edit: i think i know why i couldnt retrieve data with my relationship..i had an error with my relationship in Category Class, i have not a field for questions_id, i replaced it to:

JavaScript

and now i could get the questions with:

JavaScript

Advertisement

Answer

For your form listing probably you already have $categories = Categories::all(). Next to get all questions of this category after the submit you should first get the category and then questions for it. Let say you have category id in your form:

JavaScript

I see you are using category slug for your url, can also use it to find the category:

JavaScript

Bonus: In your service provider you can bind {category} directly to your model like this:

JavaScript

And then your category will be available in controller methods:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement