"Enhance your data management with Laravel and Vue.js by incorporating the powerful Matfish Vue-Table

Currently, I am utilizing matfish-vue-table2 along with server-side implementation.

Below is my Laravel controller where I am able to retrieve the JSON response from the 'api/articles' URL:

public function index()
{
   $articles = Article::orderBy('created_at', 'desc')->paginate();
   return ArticleResource::collection($articles);
}

This is how I'm integrating vue-table2:

<template>
  <div class="people">
    <b-card class="mb-3">
      <v-server-table :columns="columns" :options="options"></v-server-table>
    </b-card>
  </div>
</template>

<script>
  export default {
    data () {
      return{
        columns: ['id', 'title', 'body','created_at','updated_at'],
        options: {
        requestFunction: function (data) {
              let vm = this;
              return axios.get('api/article')
              .then((response) => {this.data = response.data.data; this.count = response.data.meta.total;})
              .catch(function (e) {
                  this.dispatch('error', e);
              }.bind(this));
          }
        }
      }
    },
  }
</script>

While I have been successful in populating the table, I am facing an issue with pagination and receiving the error message

TypeError: Cannot read property 'data' of undefined
. How can I resolve this?

Answer №1

Ensure that your controller includes the following code:

public function index(Request $request)
{
    $paging = $request->input('page');
    $limit = $request->input('limit');
    $querysearch = $request->input('query');
    $sorting = $request->input('orderBy');
    $sortorder = $request->input('ascending');

    $articles = Article::
        select(
            'id',
            'title',
            'body',
            'created_at',
            'updated_at'
        );

    $count = $articles->count();

    if ($querysearch) {
        $articles->where(function ($query) use ($querysearch) {
            $query->orWhere('title', 'like', '%' . $querysearch . '%');
            $query->orWhere('body', 'like', '%' . $querysearch . '%');
        });
    }

    if ($sorting) {
        $asc = $sortorder == 1 ? 'asc' : 'desc';
        $articles->orderBy($sorting, $asc);
    } else {
        $articles->orderBy('created_at', 'desc');
    }

    if ($paging == 1) {
        $articles = $articles->take($limit)->get();
    } else {
        $articles = $articles->skip($limit * ($paging - 1))->take($limit)->get();
    }        

    $data = [
        'data' => $articles,
        'count' => $count
    ];

    return json_encode($data);
}

You may want to adjust the requestFunction as shown below:

requestFunction: function (data) {
      let vm = this;
      return axios.get('api/article')
      .then((response) => {this.data = response.data; this.count = response.count;})
      .catch(function (e) {
          this.dispatch('error', e);
      }.bind(this));
  }
}

If you do not need the requestFunction, you can delete it and update your v-server-table like this:

<v-server-table url="api/article" :columns="columns" :options="options"></v-server-table>

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

Why is Reactjs axios returning a promise instead of the expected value?

I have been attempting to retrieve data from an API using axios, but all I am getting back is a Promise. The Node.js code: router.get('/isAdmin/:userId/:groupeId', async (req, res) => { let userId = req.params.userId let groupeId = ...

Storing dates as collection names is not supported in Firestore

I'm currently facing an issue trying to store stock prices in Firestore. I want the structure to resemble something similar to SQL, like this: const d1 = new Date(); const result = d1.getTime(); console.log('Epochtime',result); database.coll ...

Exploring the use of Angular with tables: applying classes dynamically using ngClass and repeating items using

My table is generated from a Web Service JSON, each row has a button to mark it for deletion. When you click the button, a JS alert displays the ID of the row element, and I also need to add the 'danger' bootstrap class to the row. Now, I can cap ...

I am facing an issue with incorporating dynamic imports in the configuration of my Vue router

Currently working on a Vue.js web page using webpack 4 and babel 6 for asset compilation. Encountering an issue when trying to use route('home', '/', () => import('../pages/home.vue')), as the compiler is throwing an error ...

Welcome to the awe-inspiring universe of Typescript, where the harmonious combination of

I have a question that may seem basic, but I need some guidance. So I have this element in my HTML template: <a href=# data-bind="click: $parent.test">«</a> And in my Typescript file, I have the following code: public test() { alert( ...

The Importance of Selenium Events and Patience

Currently, I am using Selenium to automate some testing for our company's website, but encountering issues along the way. TestItemFromSearch: (driver, part, qty) => { Search.SearchItem(driver, part); driver.findElement(By.id('enterQty ...

I am encountering difficulties with Axios GET and POST requests when using an actual host server

While everything works fine on the local server localhost:8080 in my Vue project, I encounter an issue when deploying the project to my actual host. mounted(){ axios.get('http://localhost/online-store/src/database_api/Admin/recent_product.php& ...

What could be the reason for my Angular website displaying a directory instead of the expected content when deployed on I

My current challenge involves publishing an Angular application to a Windows server through IIS. Upon opening the site, instead of displaying the actual content, it shows a directory. However, when I manually click on index.html, the site appears as intend ...

Transforming Json data into an Object using Angular 6

https://i.stack.imgur.com/JKUpL.png This is the current format of data I am receiving from the server, but I would like it to be in the form of an Object. public getOrder(): Observable < ORDERS > { return this._http.get < ORDERS > (`${thi ...

What is the process for uploading an image encoded in base64 through .ajax?

I am currently working with JavaScript code that successfully uploads an image to a server using an AJAX call. Here is the ajax call snippet that is functioning properly. $.ajax({ url: 'https://api.projectoxford.ai/vision/v1/analyses?', ...

Navigating Angular QueryList through loops

I am currently trying to gather all the images in my component and store them in an array. To achieve this, I am utilizing Angular's @ViewChildren which returns a QueryList of ElementRef: @ViewChildren('img', { read: ElementRef }) images: Q ...

Utilize a React Switch Toggle feature to mark items as completed or not on your to-do list

Currently, I am utilizing the Switch Material UI Component to filter tasks in my list between completed and not completed statuses. You can view the demonstration on codesandbox The issue I'm facing is that once I toggle a task as completed, I am un ...

Extract a selection from a dropdown menu in ReactJS

I have multiple cards displayed on my screen, each showing either "Popular", "Latest", or "Old". These values are retrieved from the backend. I have successfully implemented a filter option to sort these cards based on popularity, age, etc. However, I am u ...

How can I change the attributes of icon().abstract.children[0] in the fontawesome-svg-core api?

The issue at hand: The icon() function within the fontawesome-svg-core API is setting default properties for SVG children elements that require custom modifications. My objective: The outcome of the icon() method is an object with an "html" property, co ...

Removing an element in ReactJS

As a newcomer to React, I created an application that supports saving searches. Currently, it retrieves data from a static array data in JSON format. Unfortunately, I'm struggling with the process of removing saved searches from the list. You can vie ...

Establishing a small boutique utilizing Vue.observable for property getters

I am currently importing the createStore function into a store.js file and passing an object with state properties and mutation functions as an argument, which is working well. createStore.js import Vue from 'vue' function createStore({ state, ...

Show me a list of either only development or production dependencies in npm

When attempting to list only the production dependencies from package.json according to the npm docs, I tried: npm list -depth 0 -prod or npm list -depth 0 -only prod However, npm continues to list both dependencies and devDependencies. Can anyone sugg ...

I am looking to implement custom styles to a navigation bar element upon clicking it

When I attempted to use useState(false), it ended up applying the styles to all the other elements in the navbar. import React, { useState } from 'react'; import { AiOutlineMenu } from 'react-icons/ai'; import { Navbar, NavContainer, Na ...

Enhance user interactivity by incorporating dynamic checkboxes, radio buttons, checkbox groups, and radio button groups using Ext

Hello to all the amazing folks at Stack Overflow! I've tried searching for a solution to this issue on Stack Overflow, but I couldn't find anything helpful. Here is my model: Ext.define('soru', { extend: 'Ext.data.Model' ...

The Link Breaks the Overlay Hover Effect

Currently, the code functions as intended when you hover over or touch the thumbnail, an overlay will appear. The issue lies in the fact that to navigate to a specific URL, you have to click directly on the text. The overlay itself is not clickable and ca ...