'Livewire dependent dropdown, multiple row in a form

i have a form than can submit multiple rows using livewire. I have school level and subjects model. School level has many subjects. Subjects belongs to School level. I want to make dependent dropdown. When i select a school level, the subjects related to the school level will be loaded. If i only have one row(one entry). it would not be a problem, but when i add new row, the subjects select field will follow the first row value. How do i load subjects so that it is unique to its own row?

School Level:

<label class="required form-label">School Level</label>
<select wire:model="studentForms.{{ $index }}.level" name="level" class="form-select" required>
<option value="" selected>--Select School Level--</option>
@foreach ($schoolLevels as $schoolLevel)
   <option class="mb-2" value="{{ $schoolLevel->id }}">{{ $schoolLevel->name }}</option>
@endforeach
</select>

Subjects:

<select wire:model="studentForms.{{ $index }}.subject" name="subject" class="form-select" data-placeholder="Select Subjects" required>
<option value="" selected>--Select Subject--</option>
@foreach ($subjects as $subject)
  <option value="{{ $subject->id }}">{{ $subject->name }}</option>
@endforeach
</select>

Livewire Class:


    public function mount()
    {
        $this->subjects = collect();
    }

    public function render()
    {
        return view('livewire.form', [
            'schoolLevels' => SchoolLevel::has('subjects')->get(),
        ]);
    }

    public function updated($value, $key)
    {
        $this->subjects = Subject::where('school_level_id', $key)->get();
    }

Livewire Class



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source