I am experiencing an issue with Vue multiselect. I am trying to save the id of selected options in a database, but it seems that I am encountering an error related to Array to string conversion. I have declared both site_id and administrator in fillables. Although I am receiving an array of selected options on the controller side, I believe the problem lies within the insert method which is causing the error. I hope my question is clear.
Html:
<form @submit.prevent="addAllocateSites">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="typo__label">Select Site</label>
<multiselect v-model="form.selected_sites" :options="options"
:multiple="true"
:close-on-select="false"
:clear-on-select="false" :preserve-search="true"
placeholder="Pick Site"
name = "selected_sites"
label="asset_name" track-by="asset_name"
:class="{ 'is-invalid': form.errors.has('selected_sites') }">
<template slot="selection" slot-scope="{ values, search, isOpen }"><span
class="multiselect__single" v-if="values.length && !isOpen">{{ values.length }} Sites selected</span>
</template>
</multiselect>
<pre class="language-json"><code>{{form.selected_sites}}</code></pre>
</div>
<has-error :form="form" field="selected_sites"></has-error>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
<br>
</form>
Script:
<script>
import Multiselect from 'vue-multiselect';
import Form from 'vform';
export default {
components: {
Multiselect
},
data() {
return {
form: new Form({
selected_sites: [],
}),
options: []
}
},
methods: {
getSites() {
axios.get('api/sites').then(data => {
this.options = data.data;
console.log(data.data)
}, function (data) {
console.log(data)
});
},
addAllocateSites(){
this.form.post('api/allocate_sites').then(() => {
toast.fire({
type: 'success',
title: 'Sites Allocated Successfully'
});
});
}
},
mounted() {
this.getSites();
console.log('Component mounted.')
}
}
</script>
Controller:
public function store(Request $request)
{
$siteIds = $request->input('selected_sites');
$validation = Validator::make($request->all(), [
'selected_sites' => 'required|array',
]);
if ($validation->fails()) {
return ['Fields required'];
} else {
for ($i = 1; $i < count($siteIds); $i++) {
$sites[] = [
"site_id" => $siteIds[$i],
"administrator_id" => Auth::user()->id,
];
}
$insertData = AllocateSites::insert($sites);
if ($insertData) {
return ['Sites Allocated'];
} else {
return ['Failed to add data'];
}
}
}