0

<template>
  <div class="container">
    <div class="row mt-5 mb-3">
      <div class="col-md-10">
        <h3>Gallery</h3>
      </div>
      <div class="col-md-2">
        <button class="btn btn-success" @click="newModal">
          Add New
          <i class="fas fa-plus fa-fw"></i>
        </button>
      </div>
    </div>
    <div class="row">
      <div class="card col-md-3 mx-2 px-0" v-for="media in medias.data" :key="media.id">
        <img class="card-img-top" :src="media.thumb" alt="Card image cap" />

        <p class="card-text mb-1 mx-1 px-2 py-1" v-if="media.name">{{media.name}}</p>
        <p v-else class="text-danger card-text mb-1 mx-1 px-2 py-1">No alt name given</p>

        <div class="card-body mx-1 px-2 py-1">
          <button class="btn btn-primary btn-sm" @click="editModal(media)">Edit</button>
          <button class="btn btn-sm btn-danger" @click="deleteImg(media.id)">Delete</button>
        </div>
      </div>
    </div>


    <!-- Modal -->
    <div
      class="modal fade"
      id="addNew"
      tabindex="-1"
      role="dialog"
      aria-labelledby="addNewLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-body">
            <h4 class="text-left">Upload Here</h4>
            <vue-dropzone
              ref="myVueDropzone"
              id="dropzone"
              :options="dropzoneOptions"
              @vdropzone-complete="afterComplete"
              @vdropzone-error="uploadFailed"
            ></vue-dropzone>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal -->
    <div
      class="modal fade"
      id="edit"
      tabindex="-1"
      role="dialog"
      aria-labelledby="editLabel"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="editLabel">Edit</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <form @submit.prevent=" update()">
            <div class="modal-body">
              <div class="form-group">
                <input
                  v-model="form.name"
                  type="text"
                  name="name"
                  placeholder="Alt name"
                  class="form-control"
                  :class="{ 'is-invalid': form.errors.has('name') }"
                />
                <has-error :form="form" field="name"></has-error>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
              <button type="submit" class="btn btn-success">Update</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import vue2Dropzone from "vue2-dropzone";
import "vue2-dropzone/dist/vue2Dropzone.min.css";
export default {
  data() {
    return {
      editmode: false,
      medias: {},
      form: new Form({
        id: "",
        name: ""
      }),
      dropzoneOptions: {
        url: "/api/gallery",
        maxFilesize: 10,
        acceptedFiles: ".jpg, .jpeg, .JPG, .JPGE",
        dictDefaultMessage: "Click or Drag and Drop to upload",
        headers: {
          "X-CSRF-TOKEN": document.head.querySelector("[name=csrf-token]")
            .content
        }
      }
    };
  },
  methods: {
    uploadFailed(file, message, xhr) {
      toast({
        type: "error",
        title: "Uploading "+file.name+" failed.<br>"+message.message
      });
    },
    afterComplete() {
      Fire.$emit("AfterCreate");
    },
    update() {
      this.$Progress.start();
      // console.log('Editing data');
      this.form
        .put("api/gallery/" + this.form.id)
        .then(() => {
          // success
          $("#edit").modal("hide");
          swal("Updated!", "Information has been updated.", "success");
          this.$Progress.finish();
          Fire.$emit("AfterCreate");
        })
        .catch(() => {
          this.$Progress.fail();
        });
    },
    editModal(media) {
      this.form.reset();
      $("#edit").modal("show");
      this.form.fill(media);
    },
    newModal() {
      this.$refs.myVueDropzone.removeAllFiles();
      $("#addNew").modal("show");
    },
    deleteImg(id) {
      swal({
        title: "Are you sure?",
        text: "You won't be able to revert this!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "Yes, delete it!"
      }).then(result => {
        // Send request to the server
        if (result.value) {
          this.form
            .delete("api/gallery/" + id)
            .then(() => {
              swal("Deleted!", "Your file has been deleted.", "success");
              Fire.$emit("AfterCreate");
            })
            .catch(() => {
              swal("Failed!", "There was something wronge.", "warning");
            });
        }
      });
    },
    initialLoad() {
      axios.get("api/gallery").then(({ data }) => (this.medias = data));
    }
  },
  created() {
    this.initialLoad();
    Fire.$on("AfterCreate", () => {
      this.initialLoad();
    });
    //    setInterval(() => this.initialLoad(), 3000);
  },
  components: {
    vueDropzone: vue2Dropzone
  }
};
</script>

I have the follow following code snippet from my controller:

    public function index()
    {
        return Media::all();
    }

And from my vue component:

export default {
  data() {
    return {
      medias: {}
    };
  },
  methods: {
    initialLoad() {
      axios
        .get("api/gallery")
        .then(({
          data
        }) => (this.medias = data));
    }
  },
  created() {
    this.initialLoad();
  }
};

I'm trying get all the table rows and display it into my vue component. But with the above code I'm getting blank screen.

console.log(this.medias) also gives nothing in console.

I've also tried:

$data = Media::all();
return response() - > json($data);

And still cannot print data in table.

Route from api.php:

Route::apiResources(['gallery' => 'API\MediasController']);

Furthermore if I replace the snippet in controller with return Media::latest()->paginate(20); it does works.

0

1 Answer 1

2

all() returns a Collection while paginate() returns a Paginator. The former is your data, the latter contains your data.

In your template, you are outputting one div for each element in medias.data (line 15). This is adapted to the return value of paginate(), but doesn't work with the return value of all(). If you want to use all(), just remove .data from v-for="media in medias.data".

BTW, console.log(this.medias) won't log your data as it's inside the Vue component. Have a log at Vue devtools, it's the standard method for keeping track of data inside Vue instances.

Sign up to request clarification or add additional context in comments.

6 Comments

thanks for the explanation. Is there a way that I can show all table rows without pagination ?
Please add your template (HTML code) to your question.
That's what I expected, I've updated my answer. Now to solve your problem: What do you want to accomplish? Do you want to use all() or paginate(), or both at different times?
I want to use all()
Then just remove .data from v-for="media in medias.data"
|

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.