Rod2rick

Member Since 2 Months Ago

Experience Points
1,000
Total
Experience

4,000 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

  • Community Pillar

    Earned once your experience points ranks in the top 10 of all Laracasts users.

Level 1
1,000 XP
Jan
08
2 weeks ago
Activity icon

Started a new Conversation 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.

Dec
30
3 weeks ago
Activity icon

Replied to Laravel 8 Vuejs Image Doesn't Upload And Save To Database

@marianomoreyra I found the problem preventing the item from being saved to the database. I found the problem preventing the item from being saved to the database. So, I added in config-> App.php this lines 'providers' => Intervention\Image\ImageServiceProvider::class, 'Image' => Intervention\Image\Facades\Image::class, and now it save and image to folder and items to database. Thank you for your precious help..

Dec
28
3 weeks ago
Activity icon

Replied to Laravel 8 Vuejs Image Doesn't Upload And Save To Database

@marianomoreyra unfortunately the network console does not return any error. It recharges without sending an error

Dec
26
4 weeks ago
Activity icon

Replied to Laravel 8 Vuejs Image Doesn't Upload And Save To Database

@marianomoreyra Nothing have changed, it save the image in the storage, but nothing in the database. How can we explain that

store() {
      axios
        .post("/api/createproduit", {
          // /api/createproduit = au chemin depuis route -> api.php
          nom: this.nom,
          description: this.description,
          prix: this.prix,
          type: this.type,
          image: this.image,
          categories_id: this.categories_id,
          users_id: document
            .querySelector("meta[name='users_id']")
            .getAttribute("content"),
          headers: {
            "content-type": "multipart/form-data",
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')
              .content,
          },
        })
        .then((response) => {
          this.produits = response.data.data;
          this.loading = false;
          this.form.reset();
          window.location = response.data.redirect;
        })
        .then(location.reload())
        .catch(function (error) {
          console.log(error);
        });
    },
  },

saves in the database without save the image and

store() {
        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('users_id', document
            .querySelector("meta[name='users_id']")
            .getAttribute("content"))
      axios
        .post("/api/createproduit",data)
        .then((response) => {
          this.produits = response.data.data;
          this.loading = false;
          this.form.reset();
          window.location = response.data.redirect;
        })
        .then(location.reload())
        .catch(function (error) {
          console.log(error);
        });
    }

did not save anything. Hum it's really frustrating.

Activity icon

Replied to Laravel 8 Vuejs Image Doesn't Upload And Save To Database

@marianomoreyra , sorry to tell you that it does not work.

Dec
24
4 weeks ago
Activity icon

Replied to Can't Display Image On Bootstrap-vue Datable

@marianomoreyra , the system loads the page but slowly and many times. Indeed,after putting the v-for="produit in items" , the system becomes slow and continuously reloads the same page.

Activity icon

Replied to Laravel 8 Vuejs Image Doesn't Upload And Save To Database

@marianomoreyra , I tried your code, but unfortunately it doesn't work 100%. Unlike my code, It does save the image in folder, but does not save the product in the database. Having tried to recover your code mix with mine nothing, this time no data, neither the image, nor the data is recorded.

Dec
23
1 month ago
Activity icon

Replied to Laravel 8 Vuejs Image Doesn't Upload And Save To Database

@mvd , @hdsavani , I was able to fetch the image and save it to the product table, but in a way that I ignore the image is not fetched and save in the path. nb: this code works with blade without vuejs, but as soon as i integrate it with vuejs, it doesn't save the image. Please help me.

my code : my controller

public function store(Request $request)
    {
        $request['data'] = json_decode($request['data']);
        $produit = new Produits;
        if ($request->hasfile('image')) {
            $image = $request->file('image');
            $filename = $produit->nom . '_' . time() . '.' . $image->getClientOriginalExtension();
            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->nom = $request->get('nom');
        $produit->description = $request->get('description');
        $produit->prix = $request->get('prix');
        $produit->type = $request->get('type');
        $produit->categories_id = $request->get('categories_id');
        $produit->users_id = $request->get('users_id');
        $produit->image = $request->get('image');
        $request->file('image')->store('pictures');
        $produit->save();
        return response()->json(['success' => 'Produit enregistré avec succès']);
    }

my vuejs page

<template>
  <div class="container-fluid">
    <div class="animated fadeIn">
      <div class="row">
        <div class="col-sm-12 col-md-10 col-lg-8 col-xl-6">
          <div class="card">
            <div class="card-header">
              <i class="fa fa-align-justify"></i>
              {{ "Créer un Produit" }}
              <span class="badge float-right">
                <a
                  v-bind:href="'/listproduits'"
                  class="btn btn-sm btn-outline-info"
                  title="Liste des produits"
                >
                  <i class="fas fa-list"></i>
                </a>
              </span>
            </div>

            <div class="card-body">
              <form @submit.prevent="store" enctype="multipart/form-data">
                <div class="form-group row">
                  <label></label>
                  <input
                    class="form-control"
                    type="text"
                    placeholder="Nom du produit"
                    v-model="nom"
                    required
                    autofocus
                  />
                </div>

                <div class="form-group row">
                  <label></label>
                  <textarea
                    class="form-control"
                    id="textarea-input"
                    v-model="description"
                    rows="6"
                    placeholder="Description du Produit"
                    required
                  ></textarea>
                </div>

                <div class="input-group row">
                  <label></label>
                  <input
                    type="text"
                    class="form-control"
                    v-model="prix"
                    placeholder="Prix du produit"
                  />
                  <div class="input-group-append">
                    <span class="input-group-text">FCFA</span>
                  </div>
                </div>

                <div class="form-group row">
                  <label>Categories:</label>
                  <select
                    class="form-control"
                    v-model="categories_id"
                    @change="getCategories()"
                  >
                    <option disabled value="">
                      Sélectionner une catégorie
                    </option>
                    <option
                      v-for="categorie in categories"
                      v-bind:key="categorie.id"
                      v-bind:value="categorie.id"
                    >
                      {{ categorie.nom }}
                    </option>
                  </select>
                </div>

                <div class="form-group row">
                  <div class="col-md-9">
                    <input
                      id="file-input"
                      placeholder="Image du produit"
                      type="file"
                      name="image"
                      @change="onFileChange"
                      v-on:change="image"
                    />
                  </div>
                </div>

                <div class="form-group row">
                  <label></label>
                  <input
                    class="form-control"
                    type="text"
                    placeholder="Type du produit"
                    v-model="type"
                    required
                    autofocus
                  />
                </div>

                <div class="form-group row">
                  <label></label>
                  <input
                    class="form-control"
                    type="hidden"
                    placeholder=""
                    v-model="users_id"
                    required
                    autofocus
                  />
                </div>

                <button
                  class="btn btn-block pull-right btn btn-sm btn-outline-info"
                  type="submit"
                >
                  {{ "Valider" }}
                </button>
                <a href="" class="btn btn-block btn btn-sm btn-info">
                  {{ "Retourner" }}
                </a>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categories_id: "",
      categories: [],
      nom: "",
      description: "",
      prix: "",
      type: "",
      image: "",
      users_id: document
        .querySelector("meta[name='users_id']")
        .getAttribute("content"),
    };
  },
  methods: {
    getCategories: function () {
      axios.get("/api/get_categories").then(
        function (response) {
          this.categories = response.data;
        }.bind(this)
      );
    },
    onFileChange(e) {
      //console.log(e.target.files[0]);
      this.image = e.target.files[0].name;
      this.file = e.target.files[0];
    },
    store() {
      axios
        .post("/api/createproduit", {
          // /api/createproduit = au chemin depuis route -> api.php
          nom: this.nom,
          description: this.description,
          prix: this.prix,
          type: this.type,
          image: this.image,
          categories_id: this.categories_id,
          users_id: document
            .querySelector("meta[name='users_id']")
            .getAttribute("content"),
          headers: {
            "content-type": "multipart/form-data",
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')
              .content,
          },
        })
        .then((response) => {
          this.produits = response.data.data;
          this.loading = false;
          this.form.reset();
          window.location = response.data.redirect;
        })
        .then(location.reload())
        .catch(function (error) {
          console.log(error);
        });
    },
  },
  mounted() {
    this.getCategories();
  },
};
</script>

<style></style>

Thank you in advance for your help.

Activity icon

Replied to Can't Display Image On Bootstrap-vue Datable

@marianomoreyra when i use this code

<div
	v-for="produit in items"
	class="card"
	v-bind:key="produit.id"
>
<img
	 v-on:click="info(row.item, row.index, $event.target)"
	 v-bind="mainProps"
	 center
	 :src="'/storage/uploads/produits/' + fields.image"
	 alt="Center image"
/>

</div>

the system loads the images, but do it slowly and reloads the page every 30s. I know this is not the right method so I had to give up this route. I am very new to Vuejs and have never rowed so much to learn a framework. Otherwise from my code how can you help me correct it to improve and finally display the images. Thank you in advance

Dec
22
1 month ago
Activity icon

Replied to Laravel 8 Vuejs Image Doesn't Upload And Save To Database

@hdsavani No error is generated, the system saves the data well, but does not save the image.

Dec
21
1 month ago
Activity icon

Replied to Laravel 8 Vuejs Image Doesn't Upload And Save To Database

@hdsavani thank you very much for the tutorial, but it doesn't work for me.

Activity icon

Replied to Pagination Doesn't Work

@rod2rick , thank you very much, by the way, what is the diffrenec between mounted and method ?

Activity icon

Replied to Pagination Doesn't Work

@marianomoreyra , thank you it's work..

Activity icon

Replied to Pagination Doesn't Work

@marianomoreyra, so what do you advice me please ?

Activity icon

Started a new Conversation Pagination Doesn't Work

Hello, i trying to paginate my bootstrap-vue Datatable, but some how the pagintion doesn't work. After looking well it seems that my array items [] is the problem and the this why the pagination stay to page 1.

Her is the full code :

<b-pagination
                        v-model="currentPage"
                        :total-rows="totalRows"
                        :per-page="perPage"
                        align="fill"
                        size="sm"
                      ></b-pagination>
<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>
                          <b-img
                            v-on:click="info(row.item, row.index, $event.target)"
                            v-bind="mainProps"
                            center
                            :src="'/uploads/produits/' + fields.image"
                            alt="Center image"
                          ></b-img>
                        </div>
                      </template>
                      <template #cell(edit)="row">
                        <button
                          class="btn btn-sm btn-outline-info"
                          v-on:click="info(row.item, row.index, $event.target)"
                        >
                          <i class="fas fa-pen"></i>
                        </button>
                      </template>
                      <template #cell(delete)="row">
                        <button
                          class="btn btn-sm btn-outline-danger"
                          v-on:click="info(row.item, row.index, $event.target)"
                        >
                          <i class="fas fa-trash"></i>
                        </button>
                      </template>
                    </b-table>

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

export default {
  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: "Tout" }],
      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() {
    // Set the initial number of items
    this.totalRows = this.items.length;
  },
  methods: {
    getProduits: function () {
      axios.get("/api/listproduits").then(
        function (response) {
          this.items = response.data.data;
        }.bind(this)
      );
    },
    onFiltered(filteredItems) {
      // Trigger pagination to update the number of buttons/pages due to filtering
      this.totalRows = filteredItems.length;
      this.currentPage = 1;
    },
  },
  created: function () {
    this.getProduits();
  },
  mounted() {
    // Set the initial number of items
    this.totalRows = this.items.length;
  },
};
</script>

How can i solve this problem. Thank you in advance for the help.

Activity icon

Started a new Conversation Can't Display Image On Bootstrap-vue Datable

Hello, i can't display the image on my Bootstrap-vue Datable here is my code

<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>
                          <b-img
                            v-on:click="info(row.item, row.index, $event.target)"
                            v-bind="mainProps"
                            center
                            :src="'/uploads/produits/' + fields.image"
                            alt="Center image"
                          ></b-img>
                        </div>
                      </template>
                      <template #cell(edit)="row">
                        <button
                          class="btn btn-sm btn-outline-info"
                          v-on:click="info(row.item, row.index, $event.target)"
                        >
                          <i class="fas fa-pen"></i>
                        </button>
                      </template>
                      <template #cell(delete)="row">
                        <button
                          class="btn btn-sm btn-outline-danger"
                          v-on:click="info(row.item, row.index, $event.target)"
                        >
                          <i class="fas fa-trash"></i>
                        </button>
                      </template>
                    </b-table>

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

export default {
  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: "Tout" }],
      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() {
    // Set the initial number of items
    this.totalRows = this.items.length;
  },
  methods: {
    getProduits: function () {
      axios.get("/api/listproduits").then(
        function (response) {
          this.items = response.data.data;
        }.bind(this)
      );
    },
    onFiltered(filteredItems) {
      // Trigger pagination to update the number of buttons/pages due to filtering
      this.totalRows = filteredItems.length;
      this.currentPage = 1;
    },
  },
  created: function () {
    this.getProduits();
  },
  mounted() {
    // Set the initial number of items
    this.totalRows = this.items.length;
  },
};
</script>

What did i make wrong so that the image can't be dislay. Thank you for the help.

Dec
19
1 month ago
Activity icon

Awarded Best Reply on Cant Run Vuejs Pages Without Internet.

I found the solution. I importe the file cdn\jsdelivr... vue.js in a local js folder and now I can run thé project without internet. Thank you for the help

Activity icon

Replied to Cant Run Vuejs Pages Without Internet.

I found the solution. I importe the file cdn\jsdelivr... vue.js in a local js folder and now I can run thé project without internet. Thank you for the help

Activity icon

Replied to Cant Run Vuejs Pages Without Internet.

Yes only for jsdelivr, and before yesterday I was using it and my project was running well without internet. I just install bootstrap-vue and datatable-vue Since 2 days.

Activity icon

Started a new Conversation Cant Run Vuejs Pages Without Internet.

Hi, Since yesterday I cant run any Vuejs page without internet. I can only run blade pages in offline mode. Can someone help me so that I can use my projet without internet. Thank you.

Dec
18
1 month ago
Activity icon

Awarded Best Reply on WARNING In ./resources/js/app.js :"export 'VueRouter' Was Not Found In 'vue-router'

I had the solution to my problem. i had not set up the dependency of bootstrap-vue properly, it was in my package.jason, but not the dependency file, I had to install it via npm install bootstrap-vue. Thank you very much for your help.

Activity icon

Replied to WARNING In ./resources/js/app.js :"export 'VueRouter' Was Not Found In 'vue-router'

I had the solution to my problem. i had not set up the dependency of bootstrap-vue properly, it was in my package.jason, but not the dependency file, I had to install it via npm install bootstrap-vue. Thank you very much for your help.

Dec
15
1 month ago
Activity icon

Replied to WARNING In ./resources/js/app.js :"export 'VueRouter' Was Not Found In 'vue-router'

I still can't get the answer can someone help me ?

Activity icon

Replied to WARNING In ./resources/js/app.js :"export 'VueRouter' Was Not Found In 'vue-router'

i have try this and nothing but the same error

Activity icon

Replied to WARNING In ./resources/js/app.js :"export 'VueRouter' Was Not Found In 'vue-router'

@maverickchan i have change things like you suggest but and the same error was reported on the route.js file

"export 'VueRouter' was not found in 'vue-router'
 @ multi ./resources/js/app.js ./resources/sass/app.scss ./resources/sass/style.scss```
Dec
14
1 month ago
Activity icon

Replied to WARNING In ./resources/js/app.js :"export 'VueRouter' Was Not Found In 'vue-router'

{
    "dependencies": {
        "@coreui/chartjs": "^2.0.0",
        "@coreui/coreui": "^3.4.0",
        "@coreui/icons": "^1.0.1",
        "@coreui/icons-vue": "^1.3.5",
        "@coreui/utils": "^1.2.4",
        "@fortawesome/fontawesome-free": "^5.15.1",
        "@popperjs/core": "^2.5.4",
        "chart.js": "^2.9.3",
        "cropperjs": "^1.5.7",
        "font-awesome": "^4.7.0",
        "jquery": "^3.5.1",
        "laravel-mix": "^5.0.9",
        "laravel-vue-datatable": "^0.6.0",
        "laravel-vue-pagination": "^2.3.1",
        "mdbvue": "^6.7.2",
        "perfect-scrollbar": "1.5.0",
        "vue": "^2.6.12",
        "vue-plain-pagination": "^0.3.0",
        "vue-server-renderer": "^2.6.12",
        "vuejs-datatable": "^2.0.0-alpha.7",
        "yargs-parser": "^20.2.4"
    },
    "devDependencies": {
        "@babel/cli": "^7.12.10",
        "@babel/core": "^7.12.10",
        "@babel/plugin-proposal-object-rest-spread": "^7.9.6",
        "@babel/plugin-proposal-optional-chaining": "^7.12.7",
        "@babel/preset-env": "^7.12.10",
        "@coreui/svg-injector": "^1.0.0",
        "@coreui/vendors-injector": "^1.0.2",
        "@vue/cli-service": "^4.5.8",
        "animate.css": "^4.1.0",
        "apexcharts": "^3.22.3",
        "autoprefixer": "^9.8.0",
        "axios": "^0.19.2",
        "babel-eslint": "^10.1.0",
        "babel-plugin-transform-es2015-modules-strip": "^0.1.1",
        "bootstrap": "^4.5.2",
        "bootstrap-vue": "2.17.3",
        "browser-sync": "^2.26.7",
        "chalk": "^4.0.0",
        "clean-css-cli": "^4.3.0",
        "copyfiles": "^2.4.1",
        "cross-env": "^7.0.3",
        "echarts": "^4.9.0",
        "eslint": "^7.15.0",
        "eslint-config-xo": "^0.29.1",
        "eslint-plugin-import": "^2.20.2",
        "eslint-plugin-unicorn": "^20.0.0",
        "foreach-cli": "^1.8.1",
        "highcharts": "^7.2.2",
        "highcharts-vue": "^1.3.5",
        "imports-loader": "^0.8.0",
        "jquery": "^3.2",
        "js-beautify": "^1.11.0",
        "jsdom": "^16.2.2",
        "laravel-mix": "^5.0.1",
        "lodash": "^4.17.19",
        "minimist": "^1.2.5",
        "node-sass": "^4.14.1",
        "nodemon": "^2.0.4",
        "npm-run-all": "^4.1.5",
        "popper.js": "^1.12",
        "postcss-cli": "^7.1.1",
        "postcss-combine-duplicated-selectors": "^8.1.0",
        "postcss-merge-rules": "^4.0.3",
        "pug": "^2.0.4",
        "resolve-url-loader": "^3.1.0",
        "rimraf": "^3.0.2",
        "sass": "^1.30.0",
        "sass-loader": "^8.0.2",
        "shelljs": "^0.8.4",
        "stylelint": "^13.8.0",
        "stylelint-config-recommended-scss": "^4.2.0",
        "stylelint-config-standard": "^20.0.0",
        "stylelint-order": "^4.0.0",
        "stylelint-scss": "^3.17.2",
        "sync-glob": "^1.4.0",
        "vue": "^2.6.12",
        "vue-apexcharts": "^1.6.0",
        "vue-echarts": "^4.1.0",
        "vue-router": "^4.0.1",
        "vue-template-compiler": "^2.6.12",
        "vue-toasted": "^1.1.28",
        "vue-touch": "2.0.0-beta.4",
        "vue2-google-maps": "^0.10.7",
        "vuetable-2": "^2.0.0-beta.4",
        "vuetrend": "^0.3.4",
        "vuex": "^3.6.0"
    },
    "engines": {
        "node": ">=8"
    },
    "browserslist": [
        "last 1 major version",
        ">= 1%",
        "Chrome >= 45",
        "Firefox >= 38",
        "Edge >= 12",
        "Explorer >= 10",
        "iOS >= 9",
        "Safari >= 9",
        "Android >= 4.4",
        "Opera >= 30"
    ]
}

```
Activity icon

Replied to WARNING In ./resources/js/app.js :"export 'VueRouter' Was Not Found In 'vue-router'

@apex1 , I can really answer i took the code on a example of vuejs. Im New in vuejs. Please help to correct it.

Activity icon

Replied to WARNING In ./resources/js/app.js :"export 'VueRouter' Was Not Found In 'vue-router'

@apex1 I have also try import VueRouter from 'vue-router' And get the same error. Im using vue-router 4

Activity icon

Started a new Conversation WARNING In ./resources/js/app.js :"export 'VueRouter' Was Not Found In 'vue-router'

Im using VueJs and Laravel8 and i want to import vue-router. Her is my app.js code

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */


require('./bootstrap');

require('@fortawesome/fontawesome-free/js/all.js');

window.Vue = require('vue');


//Import View Router
import Vue from 'vue';
import {VueRouter} from 'vue-router';
import routes from './routes';

Vue.use(VueRouter);

//Import Form
import Form from './Form';
window.Form = Form;



/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('pagination', require('laravel-vue-pagination'));

Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('home-page', require('./home/Home.vue').default);
Vue.component('product-page', require('./produits/Produit.vue').default);
Vue.component('createproduit-page', require('./produits/CreateProduit.vue').default);
Vue.component('editproduit-page', require('./produits/EditProduit.vue').default);
Vue.component('showproduit-page', require('./produits/ProduitShow.vue').default);
Vue.component('produitlist-page', require('./produits/ProduitsList.vue').default);


/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */


const app = new Vue({
    el: '#app',
    router: new VueRouter(routes),
    components: { App },
});

and my route.js

import Test from './produits/Test.vue'


export default {
    mode: 'history',
    routes: [{
        path: '/Test',
        component: Test,
    }]
}

somehow i get the error

WARNING in ./resources/js/app.js : 
"export 'VueRouter' was not found in 'vue-router'
 @ multi ./resources/js/app.js ./resources/sass/app.scss ./resources/sass/style.scss

Please help me, I have already searched in vain on the internet for 2 weeks already

Dec
08
1 month ago
Activity icon

Replied to Laravel 8 Vuejs Image Doesn't Upload And Save To Database

@mvd I did it but nothing, it save the data well, but not the images.

Activity icon

Started a new Conversation Laravel 8 Vuejs Image Doesn't Upload And Save To Database

Like the title says, i can't upload image and save it to database. here is my controller

public function store(Request $request)
    {
     
        $request['data'] = json_decode($request['data']);
        $produit = new Produits;
        $produit->nom     = $request->get('nom');
        $produit->description   = $request->get('description');
        $produit->prix = $request->get('prix');
        $produit->type = $request->get('type');
        $produit->categories_id = $request->get('categories_id');
        $produit->users_id =  $request->get('users_id');
        if ($request->hasfile('image')) {
            $image = $request->file('image');
            $filename = $produit->nom . '_' . time() . '.' . $image->getClientOriginalExtension();
            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();
        return response()->json(['success' => 'Produit enregistré avec succès']);
    }

and this my vue

<form @submit.prevent="store" enctype="multipart/form-data">
                <div class="form-group row">
                  <label></label>
                  <input
                    class="form-control"
                    type="text"
                    placeholder="Nom du produit"
                    v-model="nom"
                    required
                    autofocus
                  />
                </div>

                <div class="form-group row">
                  <label></label>
                  <textarea
                    class="form-control"
                    id="textarea-input"
                    v-model="description"
                    rows="6"
                    placeholder="Description du Produit"
                    required
                  ></textarea>
                </div>

                <div class="form-group row">
                  <div class="col-md-9">
                    <input
                      id="file-input"
                      placeholder="Image du produit"
                      type="file"
                      name="image"
                      @change="onFileChange"
                      v-on:change="image"
                    />
                  </div>
                </div>

                <button
                  class="btn btn-block pull-right btn btn-sm btn-outline-info"
                  type="submit"
                >
                  {{ "Valider" }}
                </button>
                <a href="" class="btn btn-block btn btn-sm btn-info">
                  {{ "Retourner" }}
                </a>
              </form>
--------------

<script>
export default {
  data() {
    return {
      
      nom: "",
      description: "",
      image: ""
    };
  },
  methods: {
        onFileChange(e) {
      //console.log(e.target.files[0]);
      this.image = "L'image sélectionnée: " + e.target.files[0].name;
      this.image = e.target.files[0];
    },
    store() {
      const config = {
        headers: {
          "content-type": "multipart/form-data",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
        },
      };
      axios
        .post("/api/createproduit", {
          nom: this.nom,
          description: this.description,
          image: this.image,
        })
        .then((response) => {
          this.produits = response.data.data;
          this.loading = false;
          this.form.reset();
          window.location = response.data.redirect;
        })
        .then(location.reload())
        .catch(function (error) {
          console.log(error);
        });
    },
  },
  mounted() {
    this.getCategories();
  },
};
</script>

what do i do wrong so that the image connot be saved.

Activity icon

Awarded Best Reply on Save Element In Database

I just got the solution of my problem, so, i put

data() {
    return {
      categories_id: "",
      categories: [],
      nom: "",
      description: "",
      prix: "",
      type: "",
      image: "",
      users_id: document.querySelector("meta[name='users_id']").getAttribute('content'),
    };
  },

store() {
      axios
        .post("/api/createproduit", { // /api/createproduit = au chemin depuis route -> api.php
          nom: this.nom,
          description: this.description,
          prix: this.prix,
          type: this.type,
          image: this.image,
          categories_id: this.categories_id,
          users_id: document.querySelector("meta[name='users_id']").getAttribute('content')
        })

and on my controller i do

$produit->users_id =  $request->get('users_id');

in my home.blade.php i do set it like this

@if (Auth::check())
    <meta name="users_id" content="{{ Auth::user()->id }}">
@endif

and now it save the connected user. if this can help some. Thank you all for bringing me in the good way.

Activity icon

Replied to Save Element In Database

I just got the solution of my problem, so, i put

data() {
    return {
      categories_id: "",
      categories: [],
      nom: "",
      description: "",
      prix: "",
      type: "",
      image: "",
      users_id: document.querySelector("meta[name='users_id']").getAttribute('content'),
    };
  },

store() {
      axios
        .post("/api/createproduit", { // /api/createproduit = au chemin depuis route -> api.php
          nom: this.nom,
          description: this.description,
          prix: this.prix,
          type: this.type,
          image: this.image,
          categories_id: this.categories_id,
          users_id: document.querySelector("meta[name='users_id']").getAttribute('content')
        })

and on my controller i do

$produit->users_id =  $request->get('users_id');

in my home.blade.php i do set it like this

@if (Auth::check())
    <meta name="users_id" content="{{ Auth::user()->id }}">
@endif

and now it save the connected user. if this can help some. Thank you all for bringing me in the good way.

Dec
02
1 month ago
Activity icon

Replied to Save Element In Database

i used

$produit->user_id = $request->user;

and nothing, i can't get the current user on the vuejs page. The vue console is empty user_id:"", i want that this get the current user id, how can i get that please

Dec
01
1 month ago
Activity icon

Replied to Save Element In Database

@automica thank you for the advise, It's still crazy the number of tutorials that offer users_id instead of user_id, like what, we learn the right methods every day. By the way, I used users_id as user_id, and the result is the same.

Activity icon

Replied to Save Element In Database

@automica i used the same users_id in one of my table Notes, but without vuejs and it save without any problem. How can pass the user_id into your vue app when you render it first so you can pass that value back to API ? Im very lost.

Activity icon

Replied to Save Element In Database

@automica

I used $product->user_id = Auth::id(); and nothing came out, always this error of not taking into account the user. and here is the error

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'users_id' cannot be null (SQL: insert into 'produits' ('nom', 'description', 'prix', 'type', 'categories_id', 'users_id', 'updated_at', 'created_at') values (Poulet DG, Poulet DG, 2500, Test, 4, ?, 2020-12-01 11:30:46, 2020-12-01 11:30:46)) 

Is there a way to get the current user back from the vuejs page and save it by validating the form ? Thank you

Nov
30
1 month ago
Activity icon

Replied to Save Element In Database

@automica thank you very much. But now i want to save the product element with the current users 'id I uncommented the part

$produit->users_id = $user->id;

and i get this error Trying to get property 'id' of non-object

Activity icon

Started a new Conversation Save Element In Database

I want to save element in database this is my vue

<template>
  <div class="container-fluid">
    <div class="animated fadeIn">
      <div class="row">
        <div class="col-sm-12 col-md-10 col-lg-8 col-xl-6">
          <div class="card">
            <div class="card-header">
              <i class="fa fa-align-justify"></i>
              {{ "Créer un Produit" }}
            </div>
            <div class="card-body">
              <form @submit.prevent="store">
                <div class="form-group row">
                  <label></label>
                  <input
                    class="form-control"
                    type="text"
                    placeholder="Nom du produit"
                    v-model="nom"
                    required
                    autofocus
                  />
                </div>

                <div class="form-group row">
                  <label></label>
                  <textarea
                    class="form-control"
                    id="textarea-input"
                    v-model="description"
                    rows="6"
                    placeholder="Description du Produit"
                    required
                  ></textarea>
                </div>

                <div class="input-group row">
                  <label></label>
                  <input
                    type="text"
                    class="form-control"
                    v-model="prix"
                    placeholder="Prix du produit"
                  />
                  <div class="input-group-append">
                    <span class="input-group-text">FCFA</span>
                  </div>
                </div>

                <div class="form-group row">
                  <label>Categories:</label>
                  <select
                    class="form-control"
                    v-model="categories_id"
                    @change="getCategories()"
                  >
                    <option value="0">Selectionner une Catégorie</option>
                    <option
                      v-for="categorie in categories"
                      v-bind:key="categorie.id"
                    >
                      {{ categorie.nom }}
                    </option>
                  </select>
                </div>

                <div class="form-group row">
                  <div class="col-md-9">
                    <input
                      id="file-input"
                      placeholder="Image du produit"
                      type="file"
                      v-on:change="image"
                    />
                  </div>
                </div>

                <div class="form-group row">
                  <label></label>
                  <input
                    class="form-control"
                    type="text"
                    placeholder="Type du produit"
                    v-model="type"
                    required
                    autofocus
                  />
                </div>

                <button
                  class="btn btn-block pull-right btn btn-sm btn-outline-info"
                  @click="store()"
                  type="submit"
                >
                  {{ "Valider" }}
                </button>
                <a href="" class="btn btn-block btn btn-sm btn-info">
                  {{ "Retourner" }}
                </a>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categories_id: "",
      categories: [],
      nom: "",
      description: "",
      prix: "",
      type: "",
      image: "",
      user: "",
    };
  },
  methods: {
    store() {
      axios
        .post("/api/createproduit", {
          // /api/createproduit = au chemin depuis route -> api.php
          nom: this.nom,
          description: this.description,
          prix: this.prix,
          type: this.type,
          image: this.image,
          categories_id: this.categories_id,
          user: this.user,
        })
        .then((response) => {
          this.produits = response.data.data;
          this.loading = false;
          this.form.reset();
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    getCategories: function () {
      axios.get("/api/get_categories").then(
        function (response) {
          this.categories = response.data;
        }.bind(this)
      );
    },
  },
  mounted() {
    this.getCategories();
  },
};
</script>

<style></style>

and this my controller


public function store(Request $request)
     {
        //  $validatedData = $request->validate([
        //      'nom' => 'required',
        //      'description' => 'required|description|max:256',
        //      'prix' => 'required',
        //      'type' => 'required',
        //      'image' => 'required',
        //      'categories_id' => 'required',
        //  ]);
         $user = auth()->user();
         $produit = new Produits;
         $produit->nom     = $request->get('nom');
         $produit->description   = $request->get('description');
         $produit->prix = $request->get('prix');
         $produit->type = $request->get('type');
         $produit->categories_id = $request->get('categories_id');
         //$produit->users_id = $user->id;
         if ($request->hasfile('image')) {
             $image = $request->file('image');
             $filename = $produit->nom . '_' . time() . '.' . $image->getClientOriginalExtension();
             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();
         $request->session()->flash('message', 'Utilisateur modifié avec succès');
         return redirect()->route('produit.index');
     }

the console log return TypeError: can't access property "id" and the network console return SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'voluptatum' for column 'categories_id' at row 1 (SQL: insert into produits (nom, description, prix, type, categories_id, updated_at, created_at) values (Produit 01, Produit 01, 500, test, voluptatum, 2020-11-30 16:27:02, 2020-11-30 16:27:02)).

What did I do wrong. Please I need help, thank you in advance.

Nov
25
1 month ago
Activity icon

Replied to Sum Number In Vuejs

That is it i have formated the price in my ProductResource instead of

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'nom' => $this->nom,
            'description' => $this->description,
            'prix' => number_format( $this->prix, 0, '.', ' ' ),
            'type' => $this->type,
            'image' => $this->image
        ];
    }

it is

public function toArray($request)
    {
        return [
            'id' => $this->id,
            'nom' => $this->nom,
            'description' => $this->description,
            'prix' => $this->prix,
            'type' => $this->type,
            'image' => $this->image
        ];
    }

and it works properly. Thank you

@marianomoreyra , @rodrigo.pedra By the way how can i format the number properly please.

Activity icon

Replied to Sum Number In Vuejs

@marianomoreyra Yes i have checked it, may be it is the template im using, i don't know. Im using coreui as template.

Activity icon

Replied to Sum Number In Vuejs

Im using vue 2.6.12.

Activity icon

Replied to Sum Number In Vuejs

This is the entire page

<template>
  <div class="home-container">
    <h1>Articles</h1>

    <!-- search display -->
    <input
      v-model="searchKey"
      id="search"
      type="search"
      placeholder="Rechercher..."
      autocomplete="off"
    />
    <span v-if="searchKey && filteredList.length >= 1">
      {{ filteredList.length }} resultat
      <span v-if="filteredList.length >= 2">s</span>
    </span>

    <!-- cards display -->
    <div class="card-cart-container">
      <div class="card-container">
        <div
          v-for="produit in filteredList"
          class="card"
          v-bind:key="produit.id"
        >
          <div class="img-container">
            <img :src="'/uploads/produits/' + produit.image" />
          </div>

          <div class="card-text">
            <h3>{{ produit.nom }}</h3>
            <span>{{ produit.prix }} FCFA</span>
          </div>

          <div class="card-icons">
            <div class="like-container">
              <input
                type="checkbox"
                :value="produit.id"
                name="checkbox"
                v-bind:id="produit.id"
                v-model="liked"
                @click="setLikeCookie()"
              />
              <label v-bind:for="produit.id">
                <i class="fas fa-heart"></i>
              </label>
            </div>

            <div class="add-to-cart">
              <button v-on:click="addToCart(produit)">
                <i class="fas fa-plus-square"></i>
              </button>
            </div>
          </div>
        </div>

        <!-- no result message -->
        <div v-if="filteredList.length == []" class="no-result">
          <h3>Désolé</h3>
          <p>Aucun résultat trouvé</p>
        </div>
      </div>
      <!-- {{liked}} -->

      <!-- cart display -->
      <transition name="cart-anim">
        <div v-if="cart.length > 0" class="shopping-cart" id="shopping-cart">
          <h2>Commandes</h2>

          <transition-group name="item-anim" tag="div" class="item-group">
            <div
              v-for="(produit, id) in cart"
              class="item"
              v-bind:key="produit.id"
            >
              <div class="img-container">
                <img :src="'/uploads/produits/' + produit.image" />
              </div>

              <div class="item-description">
                <h4>{{ produit.nom }}</h4>
                <p>{{ produit.prix }} FCFA</p>
              </div>

              <div class="item-quantity">
                <h6>quantité : {{ produit.quantity }}</h6>

                <div class="cart-icons">
                  <button v-on:click="cartPlusOne(produit)">
                    <i class="fa fa-plus"></i>
                  </button>
                  <button v-on:click="cartMinusOne(produit, id)">
                    <i class="fa fa-minus"></i>
                  </button>
                  <button @click="cartRemoveItem(id)">
                    <i class="fa fa-trash"></i>
                  </button>
                </div>
              </div>
            </div>
          </transition-group>

          <div class="grand-total">
            <div class="total">
              <h2>Total</h2>
              <h2>{{ cartTotalAmount }} FCFA</h2>
            </div>
            <h6>Total articles : {{ itemTotalAmount }}</h6>
          </div>
          <div class="order-button">
            <button>Commander</button>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      produits: [],
      searchKey: "",
      liked: [],
      cart: [],
    };
  },
  computed: {
    filteredList() {
      return this.produits.filter((produit) => {
        return produit.nom.toLowerCase().includes(this.searchKey.toLowerCase());
      });
    },
    getLikeCookie() {
      let cookiValue = JSON.parse($cookies.get("like"));
      cookieValue == null ? (this.liked = []) : (this.liked = cookiValue);
    },
cartTotalAmount() {
    return this.cart.reduce( (acc, item) => {
        return acc + (item.quantity * item.prix)
    }, 0)
}
  },
  methods: {
    loadProduits: function () {
      axios
        .get("/api/produits")
        .then((response) => {
          this.produits = response.data.data;
          this.loading = false;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    addToCart(produit) {
      // check if already in array
      for (let i = 0; i < this.cart.length; i++) {
        if (this.cart[i].id === produit.id) {
          return this.cart[i].quantity++;
        }
      }
      this.cart.push({
        id: produit.id,
        image: produit.image,
        nom: produit.nom,
        prix: produit.prix,
        quantity: 1,
      });
    },
    cartPlusOne(produit) {
      produit.quantity = produit.quantity + 1;
    },
    cartMinusOne(produit, id) {
      if (produit.quantity == 1) {
        this.cartRemoveItem(id);
      } else {
        produit.quantity = produit.quantity - 1;
      }
    },
    cartRemoveItem(id) {
      this.$delete(this.cart, id); 
    },
  },
  setLikeCookie() {
    document.addEventListener("input", () => {
      setTimeout(() => {
        $cookies.set("like", JSON.stringify(this.liked));
      }, 300);
    });
  },
  mounted() {
    this.loadProduits();
    this.getLikeCookie();
  },
};
</script>

Activity icon

Replied to Sum Number In Vuejs

@marianomoreyra i didn't see anything on the console log

Nov
24
1 month ago
Activity icon

Replied to Sum Number In Vuejs

@marianomoreyra This

cartTotalAmount() {
      let total = 0;
      
      total = this.cart.reduce( (acc, item) => {
          return acc + (item.quantity * item.price)
      }, 0)

      return total;
    },

returns 0 with default value 0 in the vue console, and this one

cartTotalAmount() {
    return this.cart.reduce( (acc, item) => {
        return acc + (item.quantity * item.price)
    }, 0)
}

returns exactly NaN.

Activity icon

Started a new Conversation Sum Number In Vuejs

I want to sum a total of my cart, but the result return NaN here is my code

cartTotalAmount() {
      let total = 0;
      for (let item in this.cart) {
        total = total + (this.cart[item].quantity * this.cart[item].price)
      }
      return total;
    },

and

 <h2>{{ cartTotalAmount }} €</h2>

Thank you for your help.

Nov
23
2 months ago
Activity icon

Replied to Load Image From Database

I have it, it was a careless error, the real filename is produits and not productsso the correct code is <img :src="'/uploads/produits/'+produit.image" class="imageproduit"> .

Thank you very much for your assistance.

Activity icon

Replied to Load Image From Database

@tisuchi here is the error Errors compiling template: invalid expression: Invalid Unicode escape sequence in '\uploads\products\'+produit.image, Raw expression: v-bind:src="'\uploads\products\'+produit.image"