Tanmay
Tanmay

Reputation: 3159

Using vue-multiselect as an input field with laravel

I need to select multiple users in a form. So I picked a vue component called vue-multiselect. But I do not know how can I receive the selected user's ids in the $request array.

This is how I am using the component:

<multiselect
   v-model="selected"
   :options="users"
   :multiple="true"
   track-by="id"
   @open="getUsers"
   :custom-label="customLabel"
   >
</multiselect>

I am binding the options to an array of objects called users and the selected user gets pushed to the selected prop.

The getUsers method performs an axios ajax call to fetch all the users to the users array.

I tried to insert a hidden input field in the form and v-modeled it to the selected prop:

<input type="hidden" name="users" v-model="selected">

But when the form was submitted and I dd'd the request array in my Laravel controller:

dd(request()->all());

request('users') contained the value: [object Object], which is definitely not what I expected.

How do I get the ID's of all the selected users?

Upvotes: 3

Views: 5832

Answers (2)

Adam
Adam

Reputation: 28979

I assume the data users is an array of objects like this

let users = [
{id: 1, name: "john"},
{id: 2, name: "steve"}
];

Then this fixes your problem:

<multiselect 
  v-model="user" 
  name="userid"
  :options="types.map(type => type.id)" 
  :custom-label="opt => types.find(x => x.id == opt).name">
</multiselect>

The idea of this fix is, that the options property of multiselect will become a normal array of id's. Then v-model is a normal attribute and will be submitted normaly. The :custom-label will iterate for each select item through your userlist. So this is only a good idea if you have a selection with less then 100 entries I guess.

Its actually still in debate how this should be done at https://github.com/shentao/vue-multiselect/issues/432.

However, it seems the best solution is, that the options property should not be a list of objects. This implies that trackBy should also not be used.

Upvotes: 1

Sintsov Roman
Sintsov Roman

Reputation: 21

You need to use computed field for your solution, example:

<multiselect
   v-model="selected"
   :options="users"
   :multiple="true"
   track-by="id"
   @open="getUsers"
   :custom-label="customLabel"
   >
</multiselect>
<input type="hidden" name="users" :value="selectedUsers">

and for example computed field:

computed: {
            selectedUsers: function () {
                let selectedUsers = [];
                this.selected.forEach((item) => {
                    selectedUsers.push(item.id);
                });
                return selectedUsers;
            }
        },

When you send your request you will see:

  'users' => string '114,159' (length=7)

Good luck

Upvotes: 1

Related Questions