laracasts / Vue-Forms

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

Added support for file upload by using FormData #10

Open Demers94 opened 7 years ago

Demers94 commented 7 years ago

By using FormData in the data() method of the Form class, it's possible to upload files and have the same type of validation as regular data.

Example of how to use in your Vue component / JS code :

<!-- Template -->
<input type="file" name="file" @changed="fileChanged">
<span class="text-danger" v-if="form.errors.has('file')" v-text="form.errors.get('file')"></span>

<!-- Script -->
data(){
  return {
    form: new Form({
      file: '',
    })
  };
},

methods: {
  fileChanged(e){
    // Set the file to what was passed to the input[type="file"]
    this.form.file = e.target.files[0];
  }
}
bivinvinod commented 7 years ago

I was planning on doing this way. Is there any drawbacks on doing this way ? Both sparty and jeff haven't done this. @Demers94 Did you find any ?

Demers94 commented 7 years ago

Hey @bivinvinod , I've been using this (with the FormData addition) for a few months and I haven't encountered any issues/drawbacks. I'm not sure why it's not setup that way on other packages, but I find it very useful to be able to upload files and have the same validation/error handling for files.

ghost commented 5 years ago

It works! However, when I'm passing an object, Laravel doesn't read that nested object and returns null on my db.

form: new Form({
    department: {
        id: null
    },
    user: {
        email: null
    },
    first_name: null,
    middle_name: null,
    last_name: null
})

On my Laravel response:

...
department: [object Object]
...

Any workaround?

Edit: I just removed nested objects and just used Laravel's accessor.