What is the process for implementing pagination in vue-tables-2 with a Laravel REST API?

I'm looking to implement pagination on Vue server-table using a Laravel endpoint. How can I achieve this?

Below is my component setup:

<template>
    <div>
        <v-server-table :columns="columns" url="/object/find" :options="options">
        </v-server-table>
    </div>
</template>
<script>
export default {
data () {
      return {
        columns: ['name', 'type', 'created_by', 'created_at'],
        options: {
          perPage: 5,
          perPageValues: [5, 10, 15, 25, 50, 100],
          pagination: {chunk: 5},
          dateColumns: ['created_at'],
          dateFormat: 'DD-MM-YYYY HH:mm',
          datepickerOptions: {
            showDropdowns: true,
            autoUpdateInput: true,
          }
          filterable: ['name', 'type','created_by', 'created_at'],
          sortable: ['name', 'type', 'created_by', 'created_at'],
          requestAdapter (data) {
            return {
              sort: data.orderBy ? data.orderBy : 'name',
              direction: data.ascending ? 'asc' : 'desc',
              limit: data.limit ? data.limit : 5,
              page: data.page,
              name: data.query.name,
              created_by: data.query.created_by,
              type: data.query.type,
              created_at: data.query.created_at
            }
          },
          responseAdapter ({data}) {
            return {
              data,
              count: data.length
            }
          },
        }
      }
    },
 }
</script>

Laravel Controller Code:

public function findObjects(Request $request)
    {
        $objects = Objects::withTrashed();
        $sort = $request->get('sort');
        $direction = $request->get('direction');
        $name = $request->get('name');
        $created_by = $request->get('created_by');
        $type = $request->get('type');
        $limit = (int)$request->get('limit');
        $page = (int)$request->get('page');
        $created_at = $request->get('created_at');
        if ($sort !== null && $direction !== null) {
            $objects->orderBy($sort, $direction);
        }
        if ($name !== null) {
            $objects->where('name', 'like', '%' . $name . '%');
        }
        if ($created_by !== null) {
            $objects->where('created_by', 'like', '%' . $created_by . '%');
        }
        if ($type !== null) {
            $objects->where('type', 'like', '%' . $type . '%');
        }
        if ($created_at !== null) {
            $date_range = json_decode($created_at);
            $objects->whereBetween('created_at', [Carbon::parse($date_range->start), Carbon::parse($date_range->end)]);
        }

         return $objects->get();
    }

All the filters are working correctly. However, when implementing LIMIT or TAKE for pagination, it's returning only 5 items and the pagination links in the component aren't functioning as expected. What steps should I take in my controller and component to display 5 items per page?

Answer №1

Please carefully review the documentation provided here

You must provide a JSON object with two key properties:

data : array - An array of row objects with consistent keys.

count: number - Total count prior to any limitations set.

Here is an example format for your JSON response:

[ 
    "data": [
       { 
          "name": "Name1", 
          "created_at": "01-01-2019 00:00:01, 
          "updated_at": "02-01-2019 10:12:13",
          "pushed_at" : "01-01-2019 00:00:05"
       },
       { 
          "name": "Name2", 
          "created_at": "01-01-2019 00:00:01, 
          "updated_at": "02-01-2019 10:12:13",
          "pushed_at" : "01-01-2019 00:00:05"
       }, 
       { 
          "name": "Name3", 
          "created_at": "01-01-2019 00:00:01, 
          "updated_at": "02-01-2019 10:12:13",
          "pushed_at" : "01-01-2019 00:00:05"
       }
    ],
    "count":100
]

If you are encountering pagination issues with vue-table-2, make sure to include the total row count in your controller response

Modify your controller code as shown below:

public function findObjects(Request $request)
{
    $objects    = Objects::withTrashed();
    $sort       = $request->get('sort');
    $direction  = $request->get('direction');
    $name       = $request->get('name');
    $created_by = $request->get('created_by');
    $type       = $request->get('type');
    $limit      = (int)$request->get('limit');
    $page       = (int)$request->get('page');
    $created_at = $request->get('created_at');
    if ($sort !== null && $direction !== null) {
        $objects->orderBy($sort, $direction);
    }
    if ($name !== null) {
        $objects->where('name', 'like', '%' . $name . '%');
    }
    // Additional conditions and sorting if needed

    $count = $objects->count();

    $objects->offset($limit * ($page - 1))->limit($limit);

    $data = $objects->get()->toArray();

    return response()->json([
        'data'  => $data,
        'count' => $count
    ]);
}

Update your vuejs code as follows:

<template>
<div>
    <v-server-table :columns="columns" url="/object/find" :options="options">
    </v-server-table>
</div>
</template>
<script>
export default {
data () {
      return {
        columns: ['name', 'type', 'created_by', 'created_at'],
        options: {
          perPage: 5,
          // Additional options and configurations can be added here
        }
      }
    },
 }
</script>

Answer №2

If you want to implement pagination, make sure to include it in your SQL statement. For SQL Server users, utilize OFFSET/FETCH, and for MYSQL users, use LIMIT/OFFSET. Check out this link for more information:

Discover the optimal approach to paginate results in SQL Server

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

Using VueJS: Automatically scroll to a specific line in a table when the page loads

In my element framework table, I have a list of questions. I can select one to edit, make changes, and after validating, I want the page to automatically scroll to the modified question. <template> <div> <el-table :data="lis ...

Ensure that children elements are aligned to the bottom by setting the axis of the HTML

Elements positioned within a parent DIV typically flow from top to bottom. Even when using Javascript to add elements to the parent DIV, they maintain this top-to-bottom positioning. I am interested in achieving a bottom-to-top axis alignment within the pa ...

Utilizing React to connect with Metamask and share the signer across various contracts

I'm currently working on a solution for sharing signers across multiple JavaScript files. In my walletConnect.js file, I successfully connect to Metamask and retrieve an ERC20 token contract. async function connect(){ try{ const accounts = awai ...

Displaying JSON data in an HTML table cell format

Hey everyone, I need some help with the following task: I am working on displaying a list of log lines in an HTML table. Some of these lines will contain JSON strings, and I want to format the JSON data within the table when the HTML file is loaded from ...

When trying to create a MongoStore object, an error occurred because the property 'create' was not defined

I have exhausted all possible solutions I could find, but the issue remains unresolved. The error message is as follows: C:\Users\...............\server.js:35 store: MongoStore.create({ ^ TypeError: Cannot read property &a ...

Tips for properly formatting functional Vue components?

Below is a functional component that functions as intended. <template functional> <div> <input /> </div> </template> <script> export default { name: "FunctionalComponent" } </script> <styl ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

What is the way to utilize a scope variable within an ng-repeat filter?

I'm feeling a bit lost trying to navigate through this task with AngularJS. As a newbie to the framework, I'm struggling to find out how to achieve what I need. I have a group of users that I am looping through by using ng-repeat, but I can' ...

Tips for utilizing two renderCell functions in a datagrid from Material UI without encountering duplication or repetition

Utilizing Material UI, I have designed a table to showcase my data. In this setup, I am required to use renderCell for two specific properties: 'level by user' and 'level by referent'. Issue: The problem arises when Material UI displa ...

Steps for ensuring a div component appears on top of any other component (like h1 or p)

The outcome of the code below is displayed in this image: https://i.stack.imgur.com/CPDqC.png Is it possible to make the dropdown overlap on top of the 'HELLO's text, hiding the h1 and p tags? I have tried using z-index without success. Making ...

Get the PDF file and access it with Ajax technology

I am facing an issue with my action class that is responsible for generating a PDF. The code snippet shown sets the contentType appropriately. public class MyAction extends ActionSupport { public String execute() { ... ... File report = si ...

Struggling to access YouTube account via Google sign-in using Puppeteer framework

I am facing an issue with my puppeteer code where I am unable to proceed past the email page after clicking next due to some bot protection by Google advising me to "Try using a different browser...etc". Is there a way to bypass this using puppeteer? I h ...

Using a navigation bar as a structural component in React

I have a new app in development that features a search bar on every page as part of the layout. When a user conducts a search, the results are displayed and they can click on a result to view more details in a separate component. My main question is regar ...

Twilio Group MMS feature experiencing technical difficulties

I currently have a Twilio Trial account with an active number that supports SMS/MMS. My goal is to use this number for group MMS chats, but I am facing some challenges. After following a tutorial on Tut, I attempted to create a basic test using the provid ...

Using SVG Inline Style Conditionals in ReactJS

Would you say I have the conditional inline code set up correctly in this instance? The SVG icon is currently an x sign, but I want it to toggle to display a + sign. <svg viewBox='0 0 26 26' focusable='true' style={toggleShow ? { tra ...

display the table without providing a preview

Hey everyone, I am currently utilizing vue.js to develop a table and I am looking for a way to add a button that can print the data in the table without displaying a preview dialog. What modifications should I make to my javascript code in vue? Here is an ...

Add a fading transition feature to images that are loaded at a later time

I used a clever technique to create a blur effect by loading a small, lightweight image first. Once the main background image is loaded, it swaps out the 'data-src' with the actual image. However, I am facing an issue with the abrupt transition, ...

Creating dynamic grids in React.js by utilizing HTML

Currently, I am tackling one of the projects on FCC which is the Game of Life. Prior to diving in, my focus is on figuring out how to render a grid on the page. I aim to modify the table dimensions while ensuring it fits neatly within its container. The ...

encountering issues with displaying data on webpage when utilizing ajax

I've been working on adding a search feature to my user admin page, using AJAX for search functionality. However, I'm encountering an issue where I am unable to display the data on the page and keep receiving errors. Despite trying to enclose ev ...

A guide to using jqGrid: Retrieve the value of a particular cell by double clicking on a row

Is there a way to implement a feature where users can double click on any part of a row and have it open a new HTML page based on the specific content in a cell? For example, I have a table with different counties in New York listed in separate rows: Coun ...