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

namjin.21's avatar

how to save select/options inside a foreach into a database using livewire?

Hi guys, i have a for each(with 5 rows) and inside i have a select/option

 @foreach ($questions as $index => $question)
                        <div class="col-lg-6">
                            <h6>{{$question->tittle}}</h6>
                            <select wire:model="answers.{{$index}}" class="mb-3">
                                <option value=" "></option>
                                <option value="yes">YES</option>
                                <option value="no">NO</option>
                            </select>
                        </div>  
  @endforeach

i pass the value of each select into a variable= public answers=[] in my component, i use wire:model="answers.{{$index}}". i'm trying this: in the first load of the page, If no option has been selected(yes or no), I want the answers array to be saved like this = [" "," "," "," "," "] , but instead the array is empty, i cant use selected in the options (it does not work). if i select yes in the 1 and 3 row i want the answers array to be saved like this ["yes "," ","yes"," "," "], but instead the array its saved like this : {"0":"yes","2":"yes"}, if i select yes in all rows the array its saved like this: ["yes","yes","yes","yes","yes"] .i save the array in a table: quiz, in a single register and in a colums whit name: answers. after saving the answers I want to access them, and load the answers in the selects.

0 likes
1 reply
Nakov's avatar

Why don't you initialize the array with the default empty selections:

public $answers = [" ", " ", " ", " ", " "];

or if you have dynamic number of questions and the $questions are a collection you can initialize it like this:

public function mount()
{
	// or count($this->questions); 

    $this->answers = array_fill(0, $this->questions->count, " ");
}

Make sure that the questions are initialized before the mount.

1 like

Please or to participate in this conversation.