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

Tips for sending a form with the <button type="submit"> element

I created a login form and initially used <button type="submit">, but unfortunately, it was not functioning as expected. However, when I switched to using <input type="submit">, the form submission worked perfectly. Is there a JavaScript method ...

Exploring the reach of scope in a directive

Managing a controller responsible for fetching event JSON data, updating the DOM with data if available, and displaying an error message if no data is found: //Controller.js myApp.controller('EventsCtrl', ['$scope','API', fun ...

I'm looking to customize my d3.js Bar Graph by changing the color of each bar individually and adding a Scale for them. How can I

I am currently working on constructing a graph that illustrates the data for the Amount of Resources utilized Per Project by creating a bar graph. I am aiming to customize the colors of the bars so that each one has its own unique color. Currently, the col ...

Incorporate React JS seamlessly into your current webpage

As I delve into learning React and considering migrating existing applications to React, my goal is to incorporate a React component within an established page that already contains its own HTML and JavaScript - similar to how KnockoutJS's `applyBindi ...

Tips for improving the speed of loading infinite scroll pages

I am currently working on scraping over 100k rows from the provided URL. The data goes back approximately a month, loading in batches of 7-8 rows at a time. My current approach involves using a macro to scroll down the page slowly, which is effective but ...

How can I recreate this image in 3D using three.js?

I have a tower image' - but i don't know how to replicate this for3dview using thethree.js` any assistance would be greatly appreciated! Here is the image : This is my attempt : $(function () { "use strict"; var container, scene, cam ...

php script within a literal .tpl file

Is there a way to perform a json_encode within a literal javascript block in the context of a Smarty template? {literal} <script> function openWin() { var O = {php} echo json_encode($obj);{/php}; // syntax error ...

Creating a seamless thread using AngularJS

I am working on a Spring MVC application that utilizes HTML and Angular on the client side. I have a method in my Angular controller that needs to run every 5 seconds. How can I achieve this using Angular? Thank you for your assistance. $scope.inspectio ...

Having trouble with the "setValue" property being undefined error. Looking for a solution to input text into a codeMirror element using Selenium WebDriver with Java

Currently, I am attempting to input text into a textarea field that is recognized as CodeMirror. Below is the code snippet I have been working with: {... WebElement scriptField = this.getDriver().findElement(By.cssSelector(".CodeMirror-line>span")); ...

When dealing with errors in fetching JSON data, consider implementing a robust error handling strategy and

Is there a way to provide a fallback JSON string in case the fetch URL fails to connect? const Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`) ...

The concept of recursively exporting modules in Node.js modules

Looking for a way to recursively export all .hbs files in a NodeJS 14+ project main JS. I attempted the following: module.exports = () => ({ partial : __dirname + "/../partial/**.hbs", helper : __dirname + "/../helper/*.js" } ...

Unit Testing in Aurelia: Creating a Mock for a Custom Resolver

Below is the snippet of code that I am currently trying to test: import {inject} from 'aurelia-framework'; import {CrudResource, DependencyFactory} from 'utils'; let commonData = {}; @inject(DependencyFactory.of(CrudResource)) ...

Tips for Isolating and Manipulating a Single Element in Array.map() with REACT.JS

Is there a way to change the style of a specific element in an array without affecting others when a button is clicked? I've been struggling with this because every time I try, it ends up changing all elements instead of just the one that was clicked. ...

Finding differences between two 24-hour format times using moment.js

Is there a way to compare two times in 24-hour format using the code below? $("#dd_start_timing, #dd_end_timing").on('keyup change keydown', function() { var DutyDayStartTime = $("#dd_start_timing").val().trim();// 13:05 var ...

Getting the value of a JavaScript variable and storing it in a Python variable within a Python-CGI script

Is there a way to capture the value of a JavaScript variable and store it in a Python variable? I have a Python-CGI script that generates a selection box where the user can choose an option from a list. I want to then take this selected value and save it ...

Guide to deploying a React application using Material-UI and react-router

I've successfully built an application using React, Material-UI, and react-router. Below is the content of my complete package.json: { "name": "trader-ui", "version": "0.1.0", "private": true, "dependencies": { "@material-ui/core": "^3.2. ...

Exploring the use of TypeScript and Webpack to read non-JavaScript files in Node.js

I'm working on a backend NodeJS setup written in TypeScript that is using webpack for compilation. However, I encountered an error when trying to read a text file even though I confirmed that the file source/test.txt is being copied to the build fold ...

Exploring the interactive doughnut graph using SVG and Vue.js

Looking to create a unique dynamic donut chart using SVG and Vue. I want it to mirror the exact SVG format found on this webpage: (To see the animated chart, select a dish and click on ingredients) This might not have been the best approach, but it was ...

A unique authentication guard for filament authentication that consistently redirects to the login page

My StoreUser model is essentially a duplicate of the User model. In my config/auth.php file, I have created a new guard with providers and settings as follows: 'guards' => [ 'web' => [ 'driver' => 'se ...

JavaScript function to convert a string of characters into a readable time format

Is there a way to input a string in an 'input type="time"' field in my HTML code? <label class="item item-input"> <span class="input-label">Departure Time </span> <input type="time" ng-model="heur ...