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

ethar's avatar
Level 5

loop data inside jquery

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.''],
0 likes
2 replies
MohamedTammam's avatar
Level 51

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);
1 like

Please or to participate in this conversation.