While working on updating data in Model using API with Laravel and Vue.js, I encountered an issue where FormData() appears to be empty. I checked the formdata using the following code:
for (var value of formdata.values()) {
console.log(value);
}
Unfortunately, the output was empty.
Here is the result I obtained:
https://i.sstatic.net/kHFZE.jpg
This snippet shows my update function implemented on a Vue page:
getFile: function (event) {
this.image = event.target.files[0];
},
updateData: function () {
let config = {
header: {
"Content-Type": "multipart/form-data",
},
};
let formdata = new FormData();
// Append all necessary information to formdata
for (var value of formdata.values()) {
console.log(value);
}
axios
.post(
"http://localhost:8000/api/edit-pro/" + this.products.id,
formdata,
config
)
.then(() => {
//this.$router.push("/control-panel", response);
});
},
Below is the controller method responsible for updating the data:
public function updatePro(Request $request, $id)
{
$product = Product::find($id);
// Update product details
// File handling code...
try {
$product->save();
return ["msg" => "The product was updated successfully"];
} catch (Exception $error) {
return [
"msg" => "The product was not updated successfully",
"error" => $error,
];
}
}
The HTML section below uses Vue.js objects to pass to functions:
<form
id="main-contact-form"
class="contact-form row"
name="contact-form"
>
<!-- Form inputs omitted for brevity -->
<div class="form-group col-md-12">
<input
type="button"
name="submit"
class="btn btn-primary pull-right"
value="تعديل"
@click="updateData(products.id)"
/>
</div>
</form>
If you need more information or have any questions, feel free to ask. Thank you for your assistance!