I have these tables: questions
, participants
, choices
, and choice_participant
(pivot table). I displayed the questions with their choices on the user’s page (I used the radio box to select an option) and saved it to the table choice_participant
.
Sample table for "participants".
id | name |
---|---|
1 | John Doe |
2 | Philip Cruz |
3 | Mary Anne |
Sample table for "questions"
id | question | question_type |
---|---|---|
1 | Question # 01 | single_select |
2 | Question # 02 | multiple_select |
3 | Question # 03 | single_select |
Sample table for "choices"
id | question_id | choice |
---|---|---|
1 | 1 | Choice 01 |
2 | 1 | Choice 02 |
3 | 1 | Choice 03 |
4 | 2 | Choice 04 |
5 | 2 | Choice 05 |
6 | 2 | Choice 06 |
Sample table for "choice_participant (pivot table)"
id | participant_id | choice_id |
---|---|---|
1 | 1 | 1 |
2 | 1 | 4 |
Blade display
@if($question->question_type == 'single_select')
@foreach($question->choices as $choice)
<input id="choices[{{$question->id}}]" type="radio" value="{{$choice->id}}" name="choices[{{$question->id}}]">
<label for="choices[{{$question->id}}]">{{ $choice->choice }}</label>
@endforeach
@else
@foreach($question->choices as $choice)
<input id="choices[{{$question->id}}]" type="checkbox" value="{{$choice->id}}" name="choices[{{$question->id}}]">
<label for="choices[{{$question->id}}]">{{ $choice->choice }}</label>
@endforeach
@endif
Controller to save to pivot
foreach ($request->choices as $key => $choice_value) {
$choices = $participant->choices()->attach($choice_value);
}
This saves perfectly if the question type is "single_select," but in "multiple_select," it saves only one choice. I need to save all the selected choices in the checkbox in the pivot table. Hoping for your help, experts.
Here is the Actual UI
I am expecting to save all the choices that the user selected in "single_select (radio button)" and all selected options in "multiple_select (checkbox).
2
Answers
In your current implementation, you’re treating both single select (radio button) and multiple select (checkbox) inputs the same way. However, for checkboxes, the
$_POST
array will contain an array of selected values, not just a single value…modify your Blade template:
Notice the
[]
after thename
attribute for checkboxes. This allows multiple values to be sent for the same name.in your controller, you need to handle these arrays properly. When saving the choices
This change will ensure that all selected choices for
multiple_select
questions are properly saved in thechoice_participant
table.