1

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);
       }
    }
8
  • It would be helpful to see what error do you get in the developer console window. Can you add that as well please? Commented Feb 11, 2022 at 20:45
  • PUT 127.0.0.1:8000/api/categories/4/update 422 (Unprocessable Content) Commented Feb 11, 2022 at 22:00
  • message: "The given data was invalid.", errors: {title: ["The title field is required."]}} errors: {title: ["The title field is required."]} message: "The given data was invalid." Commented Feb 11, 2022 at 22:01
  • 1
    It's a known issue. See here and this so post Commented Feb 12, 2022 at 1:23
  • 1
    consider changing your axios.put to axios.post. let your route be a post route as well Commented Feb 14, 2022 at 11:06

1 Answer 1

0

Your api route is incorrect. It should be

axios.put(`/api/categories/${category.data.id}`, category.data);
Route::group(['middleware' => 'auth:sanctum'], function () {
    Route::apiResources([
        'categories' => 'App\Http\Controllers\API\CategoryController',
    ]);
});
Sign up to request clarification or add additional context in comments.

6 Comments

Unfortunately not working yet
What is the api route in api.php
Route::group(['prefix' => 'categories'], function() { Route::put('{slug}/courses/update', [CategoryCourseController::class, 'update']); });
Your routes aren't matching. See the updated answer.
I think there are no problems with routes, I found a solution in the comments above that laravel can't work with axios.put instead I should use axios.post with _method is set to put
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.