When I use axios.put method it doesn't work and there is no data is sent to the backend, in the same time when I change the axios.put method to axios.post it works well, what is the wrong? is there any mistake in the code below?
1- update component:
<template>
<Form @submit="update" enctype="multipart/form-data">
<Field type="hidden" name="_token" :value="category.csrf" />
<Field type="hidden" name="_method" value="put" />
<div class="form-group pb-2">
<label for="title">title</label>
<Field
type="text"
class="form-control bordered"
id="title"
placeholder="Enter title"
name="title"
v-model="category.title"
:validateOnInput="true"
:rules="validateTitle"
/>
<ErrorMessage name="title" />
</div>
<div class="form-group pb-2">
<label for="photo">photo</label>
<Field
type="file"
class="form-control"
id="photo"
name="photo"
accept="image/jpeg ,image/jpg , image/png "
@change="atFileChange"
:validateOnInput="true"
/>
</div>
<button type="submit" class="btn btn-success">Update</button>
</Form>
</template>
<script>
import { Form, Field, ErrorMessage } from "vee-validate";
import { mapActions } from "vuex";
export default {
components: {
Form,
Field,
ErrorMessage,
},
props: ["category"],
methods: {
...mapActions(["updateCategory"]),
atFileChange(event) {
this.category.photo = event.target.files[0];
},
update() {
//send form data to api
const data = new FormData();
data.append("title", this.category.title);
data.append("photo", this.category.photo);
data.append(
"_token",
document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content")
);
data.append("_method", "PUT");
const categoryId = this.category.id;
// This is a Vuex action which commit the the update mutation
this.updateCategory({ data: data, id: categoryId });
},
};
</script>
2- Vuex update action method:
updateCategory(context, category) {
context.commit('updateCategory', category);
}
3- Vuex update mutation method:
updateCategory(state, category) {
axios.put('api/categories/' + category.id + '/update',
category.data);
},
4- Backend controller update method:
public function update(CategoryRequest $request, $id)
{
try {
$category = Category::find($id);
// 1- Start uploading file
$path = "";
if ($request->has('photo') && $request->photo != null &&
getType($request->photo) !== 'string') {
$folder = 'categories';
$file = $request->photo;
$file->store('/', $folder);
$filename = $file->hashName();
$path = 'images/' . $folder . '/' . $filename;
}
// End uploading file
// 2- start Creating Slug
$slug = str_replace(' ', '-', $request->title);
// End Creating Slug
// 3- Start Updating category
$category->title = $request->title;
$category->slug = $slug;
$category->photo = $path;
$category->save();
// End Updating category
return response()->json(['message' => 'Category Updated Successfully'], 200);
} catch (\Exception $exp) {
return response()->json(['message' => 'error on Updating Category'], 422);
}
}
axios.puttoaxios.post. let your route be a post route as well