Having trouble accessing data in Laravel and Vue JS views

I'm currently working on displaying table data in a view using Vue.js and Laravel. Here is what I have attempted so far: This is the comment controller:

 public function index()
{
    $comment = Comment::Latest()->paginate(10);
    return new CommentResource($comment);
}

Here is my Vue.js comment script:

  export default {
    data: function() {
        return {
            comments: {}
        }
    },
    created() {
        this.loadComments();
    }
    ,
    methods: {
        loadComments(){
        axios.get("../api/comment").then(
            ({ data })=>(this.comments = data.data)
            // response => this.comments = response.data
        );
        },
    }
}

Finally, here is the HTML part of Vue Template:

 <div v-for="comment in comments" >
 {{ comment.title }}
 </div>

The error message that I receive in the browser is:

[Vue warn]: Error in render: "TypeError: Cannot read property 'title' of undefined"

In addition, I also get:

[Vue warn]: Property or method "comment" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Furthermore:

TypeError: Cannot read property 'title' of undefined

By the way, I am confident that I have the necessary API endpoint set up at http://localhost:8000/api/comment

{"current_page":1,"data":[{"id":1,"title":"asd","body":"asd","user_id":1,"user_email":"asd","status":1,"created_at":null,"updated_at":null}],"first_page_url":"http:\/\/localhost:8000\/api\/comment?page=1","from":1,"last_page":1,"last_page_url":"http:\/\/localhost:8000\/api\/comment?page=1","next_page_url":null,"path":"http:\/\/localhost:8000\/api\/comment","per_page":10,"prev_page_url":null,"to":1,"total":1}

When I console log the result with:

  axios.get("../api/comment").then(({ data }) => (console.log(data)))

I receive this output: https://i.sstatic.net/IEjLb.jpg

Answer №1

You are currently fetching data from the response. You have two options for accessing this data:

axios.get("../api/comment").then((response) => (this.comments = response.data.data)));

Alternatively, you can destructure the data property and access it directly.

axios.get("../api/comment").then(({ data }) => (this.comments = data.data)));

The reason for this is that axios returns a response object with a nested data property containing the server response. Since your server response also contains a data property, you need to use response.data.data to access it.

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

How to Utilize Raw HTML in GWT with the Power of Jquery/Javascript?

Below is the HTML code snippet: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function( ...

Tips for passing the same prop twice to a Vue component

Is it achievable with Vue to merge classes like this: const someMergedClass = 'otherClass' <Foo class="someClass" :class="someMergedClass" /> When passing a class and :class in Vue, they are merged together. I am aware ...

JavaScript button mouse enter

There seems to be an issue with this code. The button is not functioning properly after hovering over it, even though it was copied from the instructional website where it works fine. <html> <head> <title>Button Magic</t ...

Toggle checkbox feature in Bootstrap not functioning properly when placed within ng-view

When attempting to embed a bootstrap toggle checkbox within <ng-view></ng-view>, an issue arises where a regular HTML checkbox is displayed instead of the expected bootstrap toggle. Strangely, the same checkbox functions as a bootstrap toggle w ...

Preloading videos for optimal performance on mobile devices

Looking for a solution where 4 MP4/video files, each 5MB in size, can be played consecutively without gaps between them on all browsers and devices. Preferably not looking for a solution involving the replacement of video source files. The current approac ...

The resetFields() function fails to execute

While utilizing Vue3 with Element Plus to create a form, I encountered an issue with the resetFields() method not working as expected. The form is unable to automatically refresh itself. In the child component (Edit.vue): <template> <el-dialo ...

Troubleshooting JavaScript Date Problem with Internet Explorer 7

When I retrieve a Date from a web method, it comes in the format of "Mon Sep 30 07:26:14 EDT 2013". However, when I try to format this date in my JavaScript code like this: var d= SomeDate.format("MM/dd/yyyy hh:mm:ss tt"); //Somedate is coming from the we ...

Conceal when dates align

In my events list, I have dates displayed and would like to hide any end dates that are the same as the start dates. For instance; <span class="start_date">Wed 23rd January</span> <span class="end_date">Wed 23rd January</span> I ...

What could be causing my Bootstrap modal to fail to load dynamically?

I'm currently immersed in a fun side project, where data is fetched from a MySQL database and dynamically displayed. Everything seems to be running smoothly except for the modal display issue. The ID always matches, but the modal just won't open. ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

What's the best way to incorporate necessary styles into text using particular fonts?

Is there a way to set letter spacing and word spacing for text on my website with the font 'classylight'? Adding classes to each post in the site map seems like a lengthy process. To save time, I attempted to use the attribute*=style property to ...

Create a personalized Command Line Interface for the installation of npm dependencies

I am looking to develop a Node CLI tool that can generate new projects utilizing Node, Typescript, Jest, Express, and TSLint. The goal is for this CLI to create a project folder, install dependencies, and execute the necessary commands such as npm i, tsc - ...

Check the length of a ngRepeat array after the initial filtering before applying limitTo for further refinement

Currently, I am implementing pagination in my Angular application by using a custom startAtIndex filter along with the limitTo filter. My goal is to show the total number of results in the dataset, regardless of the current page. However, due to the use of ...

What is the method for extracting the href attribute from an <a class using Python Selenium?

I am attempting to extract a href from a webpage using selenium. When I utilize the browser console with this javascript command, I successfully get the desired href: document.getElementsByClassName('item-panel__title')[0].getAttribute('href ...

Sending a string array to MVC controllers through ajax

I've been struggling to pass a list of strings from a multiple select to the controller. Despite seeming like a simple requirement, I've spent hours trying to figure it out without success. I've done some research on this but haven't be ...

Exploring the power of media query breakpoints within Chakra UI's global styles

Trying to incorporate a media query breakpoint in Chakra UI global styles has presented some challenges. An attempt was made using template literals for property names, but it was discovered that this approach is not supported: import { ChakraProvider, e ...

In backbone.js, I often encounter the issue where my attributes are saved as nil when I create a

Whenever I try to add a new affiliate, the information is saved in the database but without a name. I have been struggling to fix this issue for quite some time now. class Shop.Views.AffiliatesNew extends Backbone.View template: JST['affiliates/ne ...

Combining HTML, CSS, JAVASCRIPT, and PHP for a seamless web development experience

As a beginner in web development, I have some knowledge of javascript, html, css and am currently delving into php. However, I am struggling to find comprehensive resources that show how to integrate all these languages together. I would greatly appreciat ...

Watch the video and follow along with your mouse using jQuery

Wouldn't it be cool to have a video play and follow your mouse pointer when you hover over the red box? And then once you move away, the video stops and disappears. Check out my progress so far: jsfiddle Here's the jQuery code I've used: $ ...

How is it possible that this React setter is effectively working despite the fact that it is within a stale closure

I've come across this interesting function that I need help understanding. The randomize function seems to be consistent in its behavior despite multiple renders, thanks to being wrapped in a useCallback. Each time the randomize button is clicked, it ...