'Foreach for Categories
i have this data, I want to loop with categories for each question. Right now all I can do is loop by displaying sequentially for each question (as in the image).what I want to do is loop and group them based on categories_id , if the categories_id changes it will be given a new line.
// 20220507095412
// http://127.0.0.1:8000/user/exams
[
{
"id": 16,
"ujians_id": 11,
"questions_id": 3,
"mulai": null,
"berakhir": null,
"durasi": 60,
"isAnswer": 0,
"created_at": "2022-05-07T02:53:56.000000Z",
"updated_at": "2022-05-07T02:53:56.000000Z",
"questions": {
"id": 3,
"title": "2",
"question": "<p>Sarana yang sangat masih dalam menyebabkan oposisi dunia yang sering berdampak pada intervensi asing terhadap Indonesia pada era globalisasi sekarang ini adalah...</p>",
"img": null,
"categories_id": 1,
"created_at": "2022-05-07T02:11:41.000000Z",
"updated_at": "2022-05-07T02:11:41.000000Z"
}
},
{
"id": 17,
"ujians_id": 11,
"questions_id": 1,
"mulai": null,
"berakhir": null,
"durasi": 60,
"isAnswer": 0,
"created_at": "2022-05-07T02:53:56.000000Z",
"updated_at": "2022-05-07T02:53:56.000000Z",
"questions": {
"id": 1,
"title": "13",
"question": "<p>Wahidin soedirohoesodo memilik peran penting dalam pergerakan kemerdekaan. Antara lain…22234232</p>",
"img": null,
"categories_id": 1,
"created_at": "2022-05-02T10:39:13.000000Z",
"updated_at": "2022-05-03T13:28:24.000000Z"
}
}
]
@php $no=1 @endphp
@foreach($dataUjian as $row)
@if($row->isAnswer == 0)
<button class="btn btn-primary btn-sm" onclick="getUjian({{$row->questions_id}}, {{$row->id}},{{$row->ujians->users_id}})" >{{$no++}}</button>
@else
<button class="btn btn-danger btn-sm" disabled>{{$no++}}</button>
@endif
@endforeach
Solution 1:[1]
First of all you have to make relationship from categories model to questions model. That way you'll get the data as categories and each category might have one or more questions which will group all the questions based on categories for you to loop through.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jyotishmoy |

