I am using axios to upload multiple files and some other stuff. Among this other stuff are arrays of integers (from checkboxes) and some boolean values.
At first I tried this:
axios.post(this.route, {
name: this.name,
...
photos: this.photos
})
And everything was perfect except that the backend received the photos as empty objects. So I tried the following
let formData = new FormData()
formData.append('name', this.name)
...
for(let i = 0; i < this.photos.length; i++) {
let photo = this.photos[i]
formData.append('photos['+i+']', photo)
}
axios.post(this.route, formData)
And the photos worked just fine, but other data like arrays and boolean values from radios started coming wrong. FormData transforms them into strin, and before the backend was receiving them like arrays and booleans directly, I want that. I am using Laravel as backend and the validations do not pass that way.
I managed to make the formdata send the data the way I want to. I wish there was a simpler way but here's what I've done.
let formData = new FormData()
formData.append('name', this.name)
formData.append('phone', this.phone)
formData.append('email', this.email)
formData.append('house_state', this.house_state)
// The boolean values were passed as "true" or "false" but now I pass them as "0" or "1" which is strill a string but Laravel recognizes it as an indicator of true or false
formData.append('has_lived_soon', this.has_lived_soon ? 1 : 0)
formData.append('can_rent_now', this.can_rent_now ? 1 : 0)
formData.append('beds_count', this.beds_count)
formData.append('seasonality', this.seasonality)
// Here's what I do for the arrays
for(let extra of this.extras_values) {
formData.append('extras[]', extra)
}
formData.append('estate_issues', this.estate_issues ? 1 : 0)
formData.append('road_state', this.road_state)
formData.append('usability', this.usability ? 1 : 0)
for(let heating_method of this.heating_values) {
formData.append('heating_methods[]', heating_method)
}
formData.append('heating_other', this.heating_other)
formData.append('address', this.address)
for(let i = 0; i < this.photos.length; i++) {
let photo = this.photos[i]
formData.append('photos['+i+']', photo)
}
axios.post(this.route, formData)
.then(function(response) {
console.log(response.data)
})
.catch(function(error) {
app.errors = error.response.data.errors
})