Retrieving all rows from a table using Laravel API and Vue.js

<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.

Answer №1

all() retrieves a Collection, while paginate() retrieves a Paginator. The former represents your data, whereas the latter contains your data.

When using medias.data in your template (line 15), it is structured for the return value of paginate(), not for all(). If you opt to use all(), simply remove .data from the v-for="media in medias.data".

Additionally, note that console.log(this.medias) will not display your data if it's within the Vue component. Consider utilizing Vue devtools for effective monitoring of data within Vue instances.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When utilizing a script to deliver a true or false response for jQuery's .load() function

Currently, I have found myself delving deep into jquery to manage the ajax requests in my web applications. Specifically, I am working on a bidding system in PHP that heavily relies on mod_rewrite. Using jQuery with a confirm dialog, I send an Ajax request ...

Set the class of the list item to "active" class

My approach to styling involves using a UL and li class to contain form selection options. I plan on hiding the radio button and using its value upon form submission. I have managed to enable checking the radio box when the <li> is clicked, but for s ...

Progress Bars Installation

For more detailed information, visit: https://github.com/rstacruz/nprogress After linking the provided .js and .css files to my main html file, I am instructed to "Simply call start() and done() to control the progress bar." NProgress.start(); NProgress. ...

Instructions on utilizing the transpiled "main.js" file using gulp

As a novice in Angularjs 1.0, I encountered issues with my script and decided to use gulp to compile ec6 to ec5 by implementing the code provided below. The compilation process generated the file main.js. However, I am unsure about how to connect it when l ...

Ajax sends the URL location to Python

I'm attempting to piece together some code. There are two distinct functions that I am trying to merge into a single entity. Code snippet: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> &l ...

The instance is referencing "underscore" during render, but it is not defined as a property or method

I have experience as a skilled react developer, but I've taken over a vue.js project from another developer and managed it for quite some time. Regrettably, I haven't put in the effort to learn vue properly. When using lodash, I encountered an u ...

Issue with Angular ngModel not syncing with variable changes

Currently using Angular 4 and Typescript, I have a table containing <select> elements in my template: <tr *ngFor="let task of tasksDetails"> <td>{{task.name}}</td> <td> <select class="form-control" [(ngMode ...

Troubleshooting Error: "Custom Vue component installation in Laravel 5 is not found in the npm registry"

We have decided to integrate Vue.js into our Laravel technology stack. In the app.js file, we have included the following Vue component: App.js file Vue.component('main-chart-of-accounts', require('chart_of_account.vue').default); Th ...

Add the content script to a webpage just one time

I am looking to inject a content script on context menu click in an extension manifest version 3. I need a way to determine if the script is already injected or not. If it hasn't been injected yet, I want to inject the content script. This condition m ...

Is it possible for a submission of a form to modify the content length header, resulting in the request failing?

Issue Description: After binding a submit event to an AJAX post request in order to send a predetermined key-value pair to a PHP script, the expected message indicating successful communication is not received. Despite the fact that the submit event trig ...

What causes the truncation of the backslash in the string "videos1_visualisation.mp4"?

Check out this example of AngularJS code I've created. The factory contains a list of video sources. var videoPlayer=angular.module('videoPlayer',[]) videoPlayer.controller("videoplayer",["$scope","videolist",function($scope,videolist) ...

The implementation of an onclick event in a freshly created HTML element is functioning solely on the final element

One issue I encountered was that when I generated page number buttons at the bottom of a page, the onclick event only worked with the last button created. Below is an example of how the page buttons were displayed: https://i.stack.imgur.com/wHwI0.png ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Is there a way to trigger an ajax call specifically on the textarea that has been expanded through jQuery?

Whenever I expand a textarea from three textareas, all three trigger an ajax call. Is there a way to only call the ajax for the specific expanded textarea? I tried using $(this).closest('textarea').attr('id'), but it didn't work. A ...

How to retrieve the value of an observable from a regular JavaScript array in Knockout JS?

Context In my project, I am working with a plain JavaScript array that starts off empty but gets populated with Knockout observables later on. These values are numbers and I need to compare them with values in another Knockout observable array. The issue ...

Encountering a "Method Not Allowed" error when attempting to process a Laravel Stripejs

Seeking to integrate stripe payment into my laravel app, The stripe payment form I utilized can be found at, The HTML code used is as follows: <div class="container"> <div class='row'> <div class='col-md-4' ...

Ways to utilize a singular pathway in various situations?

In my Nuxt project, I have implemented an admin dashboard with a unique layout (sidebar) using <NuxtChild> to render child routes: Admin.vue <NuxtChild :key="$route.path" /> Simplified Routes: { path: "/admin", ...

Tips on Guaranteeing AJAX Requests are Successfully Called in Sequential Order and Receive Responses in the Same Sequence

What is the best way to guarantee that AJAX requests are executed in a specific order and receive responses in the same order? ...

Despite awaiting them, promises are not resolving synchronously

I have a function that retrieves location information and returns a promise. I use mobx to manage the store, updating the this.locationStoreProp and this.hotel.subtext properties. public fetchPropertyLocation(some_input_params): Promise<any> { ...

Tips for organizing the router.js file in VueJs

With my router.js file currently reaching around 500 lines, I’m looking for a better way to structure it. { path: "/", component: () => import("./../src/views/dashboard/Dashboard.vue"), meta: { auth ...