I'm trying to make a POST Request to Laravel from Reactjs to insert into the database a product which may have some categories which is an array, also some images.
But it seems that when I send the POST Request with Content-Type: 'multipart/form-data', the laravel (or php) doesn't JSON Decode the array. Same thing for 'images'
How can I solve this?
This is my custom validation rules:
public function rules(): array
{
return [
'name' => 'required|min:3|max:255',
'title' => 'required|min:3|max:255',
'subtitle' => 'required|min:3|max:255',
'description' => 'nullable|min:10|max:1000',
'categories' => 'required|array',
'images' => 'required|array|min:1|max:10',
'images.*' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
];
}
Reactjs:
const handleUploadPictures = (event) => {
const files = event.target.files;
if (!files.length) return toast.error("You need to upload minimum 1 image.");
setProductImages(Array.from(files));
};
const createProduct = async () => {
const formData = new FormData();
formData.append("name", productName);
formData.append("title", productTitle);
formData.append("subtitle", productSubTitle);
formData.append("description", productDescription);
formData.append("categories", JSON.stringify(['sneakers', 'shoes']));
formData.append("images", JSON.stringify(productImages)); // productImages = Array.from(event.target.files);
await axios
.post(`${API_URL}/api/create/product`, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((response) => {
console.log(response.data);
return response.data;
})
.catch((error) => {
console.log(error);
return getResponseValidationErrors(error) ?? formatResponseError(error, "We could not add the product.");
});
}
I get 422 Unprocessable Content, response is:
{
"message": "The categories field must be an array. (and 1 more error)",
"errors": {
"categories": [
"The categories field must be an array."
],
"images": [
"The images field must be an array."
]
}
}