Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rod2rick's avatar

Update in Laravel VueJs

Hi, I would like to set up a CRUD, in Laravel and so far the Create, Read and Delete have worked fine. I get the error Error: Request failed with status code 500 when i want to update the product element.

Here is my code: 1- my update code in vue

updateProduit() {
        // alert (this.id);
        const config = {
        headers: {
          "content-type": "multipart/form-data",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')
            .content,
        },
      };
        axios.put("/api/updateProduit/" + this.id, config, {
            id : this.id,
            nom : this.nom,
            description : this.description,
            prix : this.prix,
            type : this.type,
            image : this.image,
            categories_id : this.categories_id
        })
        // .then(response => {
        //   this.form.reset();
        //   window.location = response.data.redirect;
        // })
        // .then(location.reload())
        .catch(function (error) {
          console.log(error);
        })
    },

the controller

// update product
    public  function updateProduit(Request $request, $id)
    {
        $produit = Produits::find($id);

        $produit->id = $request->id;
        $produit->nom = $request->nom;
        $produit->description = $request->description;
        $produit->prix = $request->prix;
        $produit->type = $request->type;
        $produit->categories_id = $request->categories_id;
        $produit->users_id = $request->users_id;
        $produit->image = $request->image;
        if ($request->hasfile('image')) {
            $image = $request->file('image');
            $originalName = $image->getClientOriginalName();
            // $fileExtension = $image->getClientOriginalExtension();
            $filename = $originalName;
            if ($produit->image && $produit->image == 'noproductimage.jpg') {
                Image::make($image)->resize(500, 500)->save(public_path('/uploads/produits/' . $filename));
            } else {
                File::delete(public_path('/uploads/produits/' . $produit->image));
                Image::make($image)->resize(500, 500)->save(public_path('/uploads/produits/' . $filename));
            }
            $produit->image = $filename;
        };
        $produit->update();
        return response()->json(['success' => 'Produit modifié avec succès']);
    }

The route

Route::put('/updateProduit/{id}', [App\Http\Controllers\Api\ProduitController::class, 'updateProduit'])->name('updateProduit');

what did i do wrong, Please i need your help, For 3 weeks, I have stagnated in the same place.

Thanks in advance

0 likes
15 replies
martinbean's avatar

@rod2rick I think you really need to look at breaking your components down; they’re far too big.

I don’t really know what it is you’re asking, and not going to comb through two massive chunks of code.

apex1's avatar

Is your Produit model supposed to be Produit or Produits ?

apex1's avatar

Pass an Id parameter to this.getProduit() in your mounted(). I don't think you produit in props either. Are you able to get the expected data?

eggplantSword's avatar

@apex1 I dont use axios but you can use this as a guide. In my edit method I clone the object and set it to the form. The form is where you would create a new item. If the key values are the same for a item being created and one being updated it should work no problem. Say it's a post:{title: '', text: ''} that is how you create it so when you edit it it should be the same parameters post:{title: 'my post', text: 'my text'}.

When saving just do an if else checking for the form.id if it doesn't exist its a new product and if it does exist it's an update.

When using this method you have to pass the item you want to edit, be it the table row item.

import _ from 'lodash';

edit(item) {
    this.form = _.cloneDeep(item);
    this.dialogVisible = true;  //if using dialogBox
},

Hope this helps

apex1's avatar

@rod2rick What happens when you replace $produit->update(); with $produit->save();? I believe the [model]->update() method is for mass assignment updates, e.g., $produit->update(['name' => 'new name']);.

Rod2rick's avatar

@apex1, I changed $produit->update(); with $produit->save(); and nothing i get the same error. By the way i have also used

public function update($id, Request $request)
    {
        $produit = Produits::find($id);
        $produit->update($request->all());

        return response()->json('Le produit a été modifié avec succès');
    }

and i get the same error : ` PUT http://localhost:2410/api/updateProduit/5 [HTTP/1.1 500 Internal Server Error 371ms] Error: Request failed with status code 500

piljac1's avatar

Check your latest log file in storage/logs. It will help you debug what is causing the 500 error and why.

Rod2rick's avatar

@piljac1 , this is the error i get on the storage/logs

local.ERROR: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id' cannot be null (SQL: update `produits` set `id` = ?, `nom` = ?, `description` = ?, `prix` = ?, `type` = ?, `image` = ?, `users_id` = ?, `categories_id` = ?, `produits`.`updated_at` = 2021-02-18 01:05:16 where `id` = 3)

local.ERROR: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'nom' cannot be null (SQL: update `produits` set `nom` = ?, `description` = ?, `prix` = ?, `type` = ?, `image` = ?, `users_id` = ?, `categories_id` = ?, `produits`.`updated_at` = 2021-02-18 01:06:55 where `id` = 3)

I can't understand i get this error..

apex1's avatar

@rod2rick In your put call (axios), switch your config and request data. axios.put('/url', { ...your_data }, config);

piljac1's avatar

Try to add info($request->all()); on top of $produit = Produits::find($id);. Then do your put request with axios and check your logs. You will see what you receive in your request. It might be the axios config instead of your data. If that's the case, swap them like @apex1 suggested. Alternatively, you can also use dd instead of info, but in that case, you will need to open the Network tab in your devtools and check what you receive as a response after you call your route.

codivores's avatar

If you want to send files with Axios, you should use a FormData object. Here is working example of something I did yesterday using POST method and this.form is an object storing my form fields.

let formData = new FormData();

Object.keys(this.form).forEach((key) => {
    if ("files" !== key) {
        formData.append(key, this.form[key]);
    }
});
for (var i = 0; i < this.form.files.length; i++) {
    formData.append("files[" + i + "]", this.form.files[i]["raw"]);
}

axios
.post(this.route_api, formData, {
    headers: {
        "Content-Type": "multipart/form-data",
    },
})
.then(
    (response) => {
    },
    (error) => {
        console.log(error);
    }
);
codivores's avatar

You maybe should do some validation in your Controller on the data received like

if (!$request->has('name')) {
    return response()->json(['errors' => [['status' => '400', 'detail' => 'Invalid payload']]], 400);
}
Rod2rick's avatar
Rod2rick
OP
Best Answer
Level 1

I got the solution of my problem Here is the solution :

<template #cell(edit)="data">
   <center>
       <button class="btn btn-sm btn-outline-info"
        v-on:click="editProduit(data.item.id)"
        data-target="#modalEdit">
        <i class="fas fa-pen"></i>
       </button>
  </center>
 </template>

the script, Get the product on the Modal

editProduit(id) {
      axios
        .get("/api/edit/" + id)
        .then((response) => {
          this.id = response.data.id;
          this.nom = response.data.nom;
          this.description = response.data.description;
          this.prix = response.data.prix;
          this.type = response.data.type;
          this.image = response.data.image;
          this.categories_id = response.data.categories_id;
          this.fournisseurs_id = response.data.fournisseurs_id;
          this.users_id = response.data.users_id;
          this.$refs.myModalRefEdit.show();
        })
        .catch((error) => console.log(error));
    },

The update method product on the Modal

    updateProduit() {
      const data = new FormData();

      data.append("nom", this.nom);
      data.append("description", this.description);
      data.append("prix", this.prix);
      data.append("type", this.type);
      data.append("image", this.image);
      data.append("categories_id", this.categories_id);
      data.append("fournisseurs_id", this.fournisseurs_id);
      data.append("users_id", this.users_id);
      const config = {
        headers: {
          "content-type": "multipart/form-data",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')
            .content,
        },
      };
      axios
        .post("/api/updateProduit/" + this.id, data, config)
        .then((response) => {
          this.form.reset();
          window.location = response.data.redirect;
        })
        .then(location.reload())
        .catch(function (error) {
          console.log(error);
        });
    },
1 like

Please or to participate in this conversation.