Level 7
I highly recommend using Js::from() function to inject arrays/objects into JavaScript. In this way, you no longer have to worry about wrong outputs.
See documentation here: https://laravel.com/docs/9.x/blade#rendering-json
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
i have this data come from eloquent
{
"id": 6,
"question": "I'd like two tickets for tomorrow night.",
"correct_answer": 16,
"answer": [
{
"id": 16,
"answer": "Afternoon and evening",
"explain_answer": null,
"question_id": 6
},
{
"id": 17,
"answer": "How much did you pay",
"explain_answer": null,
"question_id": 6
},
{
"id": 18,
"answer": "I'll just check for you.",
"explain_answer": null,
"question_id": 6
}
]
},
i want to loop it inside jquery
var allQuestions = [
@foreach($questions as $question){
"question": "{{ $question->question }}",
"options": ['Oak', 'Pine', 'Banyan', 'Palm'],
"answer": "{{ $question->correct_answer }}",
},
@endforeach
];
i to all questions successfully, but my question hop loop answers in side "options" i want options to be like this
"options": ['Afternoon and evening', 'How much did you pay', 'I'll just check for you.''],
I recommend format your data in the controller first
$formattedQuestions = $questions->map(fn($q ) => [
'question' => $q->question,
'answer' => $q->correct_answer,
'options' => $q->answer->map(fn($a) => $a->answer)
])
And in JavaScript
let allQuestions = @json($formattedQuestions);
Please or to participate in this conversation.