dstrTop1's avatar

Problems with uploading file using Vue.js 2 and Laravel 5.4

Form:

<form method="POST" v-on:submit.prevent="onSubmitForm" class="col-md-12" 
enctype="multipart/form-data"> 
    <input type="file" name="content" id="content">
    <button type="submit" class="btn btn-success col-md-offset-10">Submit</button>  
    </form> 

here is my vue code:

onSubmitForm: function(e){
    e.preventDefault();
    var diplom = this.newDiploma;
    this.$http.post('/diplomas', diplom);
}
data:{
    newDiploma:{
        content:''
    }

controller:

public function add(Request $request){
        request()->file('content')->store('images');
}

what I get is: Call to a member function store() on null Seems like controller gets no inputs from form

0 likes
7 replies
edoc's avatar

Why don't you dd(request()->all())?

I think the problem is you forgetting v-model

<input type="file" name="content" id="content" v-model="content">

I think it should fix the problem @dstrTop1

dstrTop1's avatar

@edoc , when i assign v-model to it. Vue part of page crushes, the problem now is:

File inputs are read only. Use a v-on:change listener instead.

thepassenger's avatar
Level 2

As the error is telling you, you have to listen for a change in the input field.

<input type="file" name="content" id="content" @change="newAvatar">

Then make a method:

newAvatar(event) {
               let files = event.target.files;
               if (files.length) this.newDiploma.content = files[0];
           }

Then you can post the request. I used axios but I couldn't send multipart/form-data so I had to use FormData Objects. Here is the code just in case.

postAvatar(){
    let data = new FormData()
    data.set('avatar', this.avatar)
    axios.post('/profile/avatar', data)
            .then(response => {
            //Do stuff
             }) 
             .catch(error => console.log(error));
}

Hope this helps you. Cheers

2 likes
dstrTop1's avatar

@thepassenger , okay, the method works! but i receive empty value in controller

    //Call to a member function store() on null
        request()->file('content')->store('/images');

and also is formData the only right solution here? why i cant send it like this?

onSubmitForm: function(
    e.preventDefault();
    diploma = this.newDiploma;
    this.$http.post('/diplomas', diploma);

thanks!

thepassenger's avatar

When I made that snippet I looked a lot between posts to find that solution. I know I couldn't make it work with axios. Have you tried to change the headers?

this.$http.post('/diplomas', diploma, {
   headers: {
       'Content-Type': 'multipart/form-data'
   }
})

Also make sure the diploma is an object. Check with the dev tools to see if you are submitting empty data in the request.

Please or to participate in this conversation.