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

Rod2rick's avatar

Delete edit row and display image in Boostrap-vue Datable

Hi, im looking how to delete and Edita row in Boostrap-vue Datable this is my Controller

// edit post
    public function edit($id)
    {
        $produit = Produits::find($id);
        return response()->json($produit);
    }


    // update post
    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');
    }

    // delete post
    public function delete($id)
    {
        $produit = Produits::find($id);
        $produit->delete();

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

and this my vue


<template>
<b-table
                      :striped="striped"
                      :bordered="bordered"
                      :borderless="borderless"
                      :outlined="outlined"
                      :sort-by.sync="sortBy"
                      :sort-desc.sync="sortDesc"
                      :current-page="currentPage"
                      :per-page="perPage"
                      :filter="filter"
                      :small="small"
                      :hover="hover"
                      :dark="dark"
                      :fixed="fixed"
                      :foot-clone="footClone"
                      :no-border-collapse="noCollapse"
                      :items="items"
                      :fields="fields"
                      :head-variant="headVariant"
                      :table-variant="tableVariant"
                    >
                      <template #cell(image)="row">
                        <div>
                          <img
                            v-on:click="
                              info(row.item, row.index, $event.target)
                            "
                            v-bind="mainProps"
                            center
                            :src="'/uploads/produits/' + fields.image"
                            alt="Produit image"
                          />
                          <!-- <div>
                              <vue-load-image>
                                  <img slot="image" src="./image.png"/>
                                  <img slot="preloader" src="./image-loader.gif"/>
                                  <div slot="error">error message</div>
                              </vue-load-image>
                          </div> -->
                        </div>
                      </template>
                      <template #cell(edit)="row">
                        <a
                          class="btn btn-sm btn-outline-info"
                          v-on:click="info(row.item, row.index, $event.target)"
                        >
                          <i class="fas fa-pen"></i>
                        </a>
                      </template>
                      <template #cell(delete)="row">
                        <button
                          class="btn btn-sm btn-outline-danger"
                          v-on:click="deleteProduct(row.item.id)"
                        >
                          <i class="fas fa-trash"></i>
                        </button>
                      </template>
                    </b-table>>
              <div class="row">
                <div class="col-xs-12 form-inline">
                  <datatable-pager
                    v-model="page"
                    type="abbreviated"
                    :per-page="per_page"
                  ></datatable-pager>
                </div>
              </div>
</template>

<script>
import Vue from "vue";
import { BootstrapVue, IconsPlugin } from "bootstrap-vue";

// Install BootstrapVue
Vue.use(BootstrapVue);
// Optionally install the BootstrapVue icon components plugin
Vue.use(IconsPlugin);

import VueLoadImage from "vue-load-image";

export default {
  components: {
    "vue-load-image": VueLoadImage,
  },
  data() {
    return {
      filter: "",
      fields: [
        { key: "image", label: "" },
        { key: "nom", label: "Nom", sortable: true },
        {
          key: "description",
          label: "Description",
          sortable: true,
          sortDirection: "desc",
        },
        { key: "prix", label: "Prix", sortable: true },
        { key: "edit", label: "" },
        { key: "delete", label: "" },
      ],
      items: [],
      mainProps: {
        width: 55,
        height: 55,
        class: "my-5",
      },
      tableVariants: [
        "primary",
        "secondary",
        "info",
        "danger",
        "warning",
        "success",
        "light",
        "dark",
      ],
      striped: false,
      bordered: false,
      borderless: false,
      outlined: false,
      small: false,
      hover: false,
      dark: false,
      fixed: false,
      footClone: false,
      headVariant: null,
      tableVariant: "",
      noCollapse: false,
      totalRows: 1,
      currentPage: 1,
      perPage: 5,
      pageOptions: [5, 10, 15, 25, 100, { value: 1000, text: "Toutes" }],
      sortBy: "",
      sortDesc: false,
      sortDirection: "asc",
      filterOn: [],
    };
  },
  computed: {
    sortOptions() {
      // Create an options list from our fields
      return this.fields
        .filter((f) => f.sortable)
        .map((f) => {
          return { text: f.label, value: f.key };
        });
    },
  },
  mounted() {
    axios.get("/api/listproduits").then(
      function (response) {
        this.items = response.data.data;
        this.totalRows = this.items.length;
      }.bind(this)
    );
  },
  methods: {
    onFiltered(filteredItems) {
      // Trigger pagination to update the number of buttons/pages due to filtering
      this.totalRows = filteredItems.length;
      this.currentPage = 1;
    },
    getProduictImage() {
      return "";
    },
    deleteProduct(id) {
        this.axios
        .delete(`api/delete/${id}`)
        .then(response => {
            let i = this.items.map(item => item.id).indexOf(id); // find index of your object
            this.items.splice(i, 1)
            });
        },
  },
  created: function () {
    this.getProduits();
  },
};
</script>

Somehow, it's not work. Thank you in advance for your help.

0 likes
1 reply
Rod2rick's avatar
Rod2rick
OP
Best Answer
Level 1

I found the solution, so this is it : The table code

<template #cell(image)="data">
                        <div>
                          <center>
                            <button
                              v-on:click="getProduit(data.item.id)"
                              data-target="#modalShow"
                            >
                              <img
                                class="c-avatar-prod"
                                center
                                :src="'/uploads/produits/' + data.item.image"
                                alt="Produit image"
                              />
                            </button>
                          </center>
                        </div>
                      </template>
                      <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>
                      <template #cell(delete)="data">
                        <center>
                          <button
                            class="btn btn-sm btn-outline-danger"
                            v-on:click="getID(data.item.id)"
                          >
                            <i class="fas fa-trash"></i>
                          </button>
                        </center>
                      </template>

The script code for get product

getProduit(id) {
      // alert (id);
      axios
        .get("/api/show/" + 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.fournisseurs_id = response.data.fournisseurs_id;
          this.users_id = response.data.users_id;
          this.$refs.myModalRefShow.show();
        })
        .catch((error) => console.log(error));
    },

The script code for edit product

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 script code for update product

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);
        });
    },

The script code for delete product

deleteItem(id) {
      axios
        .delete("/api/delete/" + id)
        .then((response) => {
          const index = this.items.findIndex((produit) => produit.id === id); // find the product index
          if (~index)
            // if the product exists in array
            this.items.splice(index, 1); //delete the product
          window.location = response.redirect;
        })
        // .then(location.reload())
        .catch(function (error) {
          console.log(error);
        });
      this.$refs.myModalRefDelete.hide();
    },

The Controller

// edit product for select product
    public function edit($id)
    {
        $produit = Produits::find($id);
        return response()->json($produit);
    }

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

        // $produit->id = $request->input('id');
        info($request->all());
        $produit->nom = $request->nom;
        $produit->description = $request->input('description');
        $produit->prix = $request->input('prix');
        $produit->type = $request->input('type');
        $produit->categories_id = $request->input('categories_id');
        $produit->fournisseurs_id = $request->get('fournisseurs_id');
        $produit->users_id = $request->input('users_id');
        $produit->image = $request->input('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->save();
        dd($produit);
        return response()->json(['success' => 'Produit modifié avec succès']);
    }

    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');
    }

    // delete product
    public function delete($id)
    {
        $produit = Produits::find($id);
        $produit->delete();

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

    // show product
    public function show($id)
    {
        $produit = Produits::find($id);
        return response()->json($produit);
    }

Please or to participate in this conversation.