I'm trying to make a simple User Avatar update using vue and laravel and I can't figure what I'm doing wrong here.
I have a vue component with this form and this script:
<form @submit.prevent="updateAvatar" action="#" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label name="task-title">Incarca poza:</label>
<input @change="newAvatar" id="avatar" type="file" name="avatar">
</div>
<button type="submit" class="btn btn-primary general-task-btn">Actualizeaza</button>
</form>
<script>
export default{
props: ['userid'],
data(){
return{
avatar: {
}
}
},
methods: {
newAvatar(event) {
let files = event.target.files;
if (files.length) this.avatar = files[0];
},
updateAvatar: function () {
let data = new FormData();
data.append('file', this.avatar);
axios.put('/api/user/updateAvatar', data)
.then(res => {
console.log(res);
})
.catch(error => console.log(error));
// window.location.href = "/profile";
}
}
}
Controller function:
public function updateAvatar(Request $request)
{
$user = Auth::user();
$avatar = $request->file('file');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save( public_path('/uploads/avatars' . $filename) );
$user->avatar = $filename;
$user->save();
}
What I really don't know is how to access that formData that I sent with axios. The server tells me that is empty. I tried to console.log the formData before making the put request but I get an empty obj even if the content is in the avatar object. As I read online, you can't see the content of a formData so I can't figure if the data is being sent correctly or not. Maybe you guys can make this clear for me.
request headerswhat is thecontent type? You also absolutely can see what's in yourformDataby callingformData.entries(). You can walk over it usingfor(pair of formData.entries()) { console.log(pair) }as well. Just need to use newer version of chrome/firefox, or a polyfill in older browsers.'content-type': 'multipart/form-data'