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

kazimmusani's avatar

is there any way to insert text array and only selected checkbox value

Its urgent please help. I want to insert multiple checkboxes and input text fields but the issues is if i am filling 3 input fields in sequence and select 2 check boxes 1st and 3rd than below function will add all checkbox vales but i want to skip the 2nd value of check box only because its not selected.

text field:

<input id="answer" type="text" name="answer[]">

Checkbox:

<input id="ifcorrect" type="checkbox" name="ifcorrect[]">    

values want to insert:

input: A     Checkbox: selected
input: B     Checkbox: not selected
input: C     Checkbox: selected

in db i want to insert as below

A    1
B    0 //0 because its not selected
C    1

i am using below but it is not working

foreach ($data['answer'] as $key => $value) {

    $answer = new Answer();
    $answer->answer = $value;
    $answer->correct = $data['correct'][$value];

    $question->answer()->save($answer);
}
0 likes
5 replies
Snapey's avatar

change the names of your fields

<input id="answer" type="text" name="answers[]text">

<input id="ifcorrect" type="checkbox" name="answers[]ifcorrect">

now you will get array of answers, each with an ifCorrect set

foreach ($data['answers'] as $answer) {

    if(isset($answer['ifCorrect'])) {
          $ans= new Answer();
          $ans->answer = $answer['text'];
          $ans->correct = true;

          $question->answer()->save($ans);
    }
}
kazimmusani's avatar

getting error

 Invalid argument supplied for foreach()
kazimmusani's avatar

data comes from blade form the actual issue is its insert only checked checkboxes but i want to insert uncheck boxes also if checked value should be insert 1 otherwise 0

MichalOravec's avatar

Use hidden inputs for that, like this 2 years old @snapey answer

https://laracasts.com/discuss/channels/laravel/how-to-pass-checkbox-value-0-if-not-checked-and-1-if-checked?page=1#reply=355362

Note: If a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked); the value is not submitted to the server at all.

Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

Please or to participate in this conversation.