0

I'm trying to access an array on a multipart-form-data request.

On my js code I add to the formData the object that I need this way:

for (const key in property) {
    if (typeof property[key] !== 'undefined') {
        console.log(key, property[key]);
        formData.append(`property[${key}]`, property[key]);
    }
}

The property has the array images and the value is an array like this:

enter image description here

Also in the same forData I send all the data from the images that I want to handle, and in this case the property contains an array of objects that are images previously stored in the database. So, in my controller I have to following

 // Images that are already in database
 $propertyData = $request->input('property');
 $images = isset($propertyData['images'])? $propertyData['images'] : []
 foreach($images as $i) {
    $image = Image::find((int)$i['id']);
    if ( !is_null($image) ) {
        $image->update($i);
    }
}

But I got the error: Invalid argument supplied for foreach()

I've tried to even convert each image on the javascript code to an array like the property, but i got the same error.

Jacobo
  • 1,259
  • 2
  • 19
  • 43

1 Answers1

0

You cannot directly append objects or arrays to FormData. You must add the keys and values one by one.

A way to do that is like so:

var formData = new FormData;
var arr = ['this', 'is', 'an', 'array'];
for (var i = 0; i < arr.length; i++) {
    formData.append('arr[]', arr[i]);
}

I use a helper function (note that this is in ES6 syntax) to do this:

export function appendFormdata(formData, data, previousKey) {
    if (data instanceof Object) {
        Object.keys(data).forEach(key => {
            const value = data[key];
            if (previousKey) {
                key = `${previousKey}[${key}]`;
            }
            if (value instanceof Object && !Array.isArray(value) && !(value instanceof File)) {
                return appendFormdata(formData, value, key);
            }
            if (Array.isArray(value)) {
                value.forEach((val, i) => {
                    return appendFormdata(formData, val, `${key}[${i}]`);
                });
            } else {
                formData.append(key, value);
            }
        });
    }
}

For more details refer: appending array to FormData and send via AJAX and Convert JS Object to form data

Paras
  • 9,258
  • 31
  • 55
  • Yeah, but this is an array inside another object. I’ve also tried that on each object inside my property object. – Jacobo Oct 18 '18 at 23:24
  • The only values you can directly append are strings. No arrays or objects or nested objects/arrays are allowed – Paras Oct 18 '18 at 23:25
  • Refer the [docs](https://developer.mozilla.org/en-US/docs/Web/API/FormData/append). You can only append a `USVString` or `Blob` in FormData – Paras Oct 18 '18 at 23:27
  • Yeah but it’s working. I mean retrieving all the data from the property. I just need to find the correct way to iterate that property – Jacobo Oct 19 '18 at 00:52
  • Thanks, I solved it doing what you are saying, but keeping the data in a single object. `property.images.map((image, index) => { for (const key in image) { formData.append(`property[images][${index}][${key}]`, image[key]); }});` – Jacobo Oct 19 '18 at 01:38