Multiple select inputs with the same name Laravel

Viewed 91

So I have this problem where I wanted to use multiple select inputs with the same name to store data into the database.

So for that I made different select inputs, the first will show the rest depending on the option selected, for example (this is just an example, not my real code):

The main select input will be like this:

<select name="users" required>
     <option value="user_one">Mike</option>
     <option value="user_two">Pablo</option>
</select>

and when we select some of the options above, like Mike, it will show another select input :

<select name="lang_specif[]" required>
     <option value="php">php</option>
     <option value="python">python</option>
     <option value="js">js</option>
</select>

if we select the Pablo it will show another select input:

<select name="lang_specif[]" required>
     <option value="php">php</option>
     <option value="python">python</option>
     <option value="js">js</option>
</select>

The thing is, both of them have the same name and it returns an array when submitting,

In my real code I have multiple select inputs, that depend on the option selected, it will show one or another, I can't use different names, because it causes me to add 12 columns to the database, and if I can access it and get the actual value that has been submited it will only require me 2.

1 Answers
<form>
<select name="users" required>
     <option value="user_one">Mike</option>
     <option value="user_two">Pablo</option>
</select>


<!-- Select 1 -->
<select name="lang_specif[]" class="hidden">
     <option value="php">php</option>
     <option value="python">python</option>
     <option value="js">js</option>
</select>

<!-- Select 2 -->
<select name="lang_specif[]" required>
     <option value="php">php</option>
     <option value="python">python</option>
     <option value="js">js</option>
</select>

<input type="submit" />
</form>

You can distinguish them by checking which of them is hidden:

let form = document.querySelector('form');
let userSelect = document.querySelector('[name="users"]');

form.addEventListener('submit', function() {
    let user = userSelect.value
    let lang_specif = document.querySelector('[name="lang_specif[]"]:not(.hidden) option:selected').value;
    if (lang_specif === null) {
        // error
    }
}

userSelect.addEventListener('change', function(evt) {
    let select = document.getElementsByName('lang_specif[]')[evt.target.selectedIndex]
    select.classList.remove('hidden')
    select.required = true

    let notSelect = document.getElementsByName('lang_specif[]')[!evt.target.selectedIndex]
    notSelect.classList.add('hidden')
    notSelect.removeAttribute('required')
})
.hidden {
    display: none;
}
Related