I’m a newbie and i’m trying to create a rest project with Vue and Laravel and I have a form that allows to send an image, but when I try to store it in the db, I got an error:
"Request failed with status code 422"
and
"The image must be an image"
I can’t figure how to solve it, any suggestion?
<script>
export default {
data() {
return {
title: undefined,
year: undefined,
director: undefined,
plot: undefined,
rating: undefined,
image: null,
};
},
methods: {
insertedFile(e) {
this.image = e.target.files[0];
},
addFilm() {
const formData = new FormData;
formData.set('image', this.image)
console.log(formData.get('image'));
//
axios
.post("/api/films", {
title: this.title,
year: this.year,
director: this.director,
plot: this.plot,
rating: this.rating,
image:formData
})
.then((response) => {
console.warn(response)
});
},
},
};
</script>
<template>
<form @submit.prevent="addFilm()" enctype="multipart/form-data" method="post">
<input type="text" name="title" placeholder="title" v-model="title" />
<input type="number" name="year" placeholder="year" v-model="year" />
<input
type="text"
name="director"
placeholder="director"
v-model="director"
/>
<input type="text" name="plot" placeholder="plot" v-model="plot" />
<input
type="number"
name="rating"
placeholder="rating"
v-model="rating"
/>
<input
type="file"
name="image"
id="image"
@change="insertedFile($event)"
/>
<button type="submit">Submit</button>
</form>
</template>
Controller:
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'year' => 'required',
'plot' => 'required',
'director' => 'required',
'rating' => 'required',
'image' => 'image|mimes:jpg,png,jpeg,svg|max:2048'
]);
$film = new Film([
'title' => $request->title,
'year' => $request->year,
'plot' => $request->plot,
'director' => $request->director,
'rating' => $request->rating,
"image" => $request->file('image')->store('images', 'public')
]);
$film->save();
return redirect()->route('home')
->with('success', 'film created successfully!');
}
2
Answers
Try combining your payload (data) with your
formData
and setting thecontent-type
header of youraxios
request tomultipart/form-data
:you’re passing the FormData object as image.
in order to make it work, you should give axios the FormData object containing all the data you want to send.
addFilm method should look like this: