laracasts / Vue-Forms

https://laracasts.com/series/learn-vue-2-step-by-step/episodes/19
396 stars 204 forks source link

$request is empty when using multipart/form-data #19

Open YoussF opened 6 years ago

YoussF commented 6 years ago

Hello,

I've been working with jeffrey's Form.js for a while now without any issue. Until i had to add a input type file in my registration form for the user to upload an avatar while creating the account. So i had to adapt a little bit the form.submit() so that i can tell axios to use "multipart/form-data" like so :

let config = { headers: { 'Content-Type': 'multipart/form-data' } }
axios[requestType](url, this.data(), config)

The minute i've done that, the hole form stopped working. I had tried to troubleshoot the issue by doing a dd($request). And now i seems like $request is empty which was before that change to axios, filled with all the form fields as before.

So i asked our friend Google, and i found this interesting issue https://github.com/laravel/framework/issues/13457 which seems to be somehow related.

To be honest, i didn't quite understood why framework/issues/13457 status is closed. The workaround doesn't seems to be working. The only difference between the reported issue and my case, is that i use the post method to submit the form as they are using put/patch

I really tried my best to resolve this issue by my own. But i can't and now honestly i'm stuck :(

saulchelewani commented 5 years ago

In my case I passed the payload as a FormData object which worked. I created a setFormData method

setFormData(data) {
  let formData = new FormData();
  for (let field in data) {
    formData.append(field, data[field]);
  }
  return formData;
}

and the submit method becomes

submit(requestType, url) {
  return new Promise((resolve, reject) => {

    // pass the response from setFormData() as payload

    axios[requestType](url, this.setFormData(this.data()))
      .then(response => {
        this.onSuccess(response.data);

        resolve(response.data);
      })
      .catch(error => {
        this.onFail(error.response.data);

        reject(error.response.data);
    });
  });
}