Skip to content
Advertisement

How to get all the selected values from a multiselect input?

I am using Laravel and I tried to used die(var_dump('$request->input('users'))); to check the data that are selected using a multiselect input. When I selected all 3 users, the output was just showing the last user id like this

array(1) {
  [0]=>
  string(1) "3"
}

This is the input. The name was set as user[0] because the inputs can be multiple depending on the user how many multiselect input is needed

<select class="form-control user" id="user" name="user[0]" multiple="">
    @foreach ($users as $user)
        @if (old('user') == $user->id)
            <option value="{{ $user->id }}" selected="">{{ ucwords($user->name) }}</option>
        @endif
    @endforeach
</select>

And this below if from the controller

$users = array();
$user = $request->input('user');
$user = implode(',', $user);

Advertisement

Answer

You should have the input name setup as the syntax for adding an element to an array:

 name="user[]"

Then you will get your array from $request->input('user', []);

If you are going to have multiple different selects you can use the index in them if you wish:

 name="user[0][]"
 name="user[1][]"
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement