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

Transform text that represents a numerical value in any base into an actual number

Looking to convert a base36 string back to a double value. The original double is 0.3128540377812142. When converting it to base 36: (0.3128540377812142).toString(36); The results are : Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi Firefox: 0.b9ginb6s73e Now, h ...

Vue's watch function failing to trigger

Experiencing issues with Vue watch methods not triggering for certain objects even when using deep:true. Within my component, I am passed an array as a prop containing fields used to generate forms. These forms are dynamically bound to an object named cru ...

Identifying the specific npm script command that was executed

My index.js file contains scripts that can be executed like the ones below: "scripts": { "lint": "eslint .", "serve": "firebase emulators:start --only functions", "inspect": "firebase emulators:start --inspect-functions", "deploy": "fire ...

Remove the default selection when a different option is chosen using Bootstrap

I have implemented the Bootstrap-select plugin () for a multiple select dropdown on my website. Upon page load, there is a default option that is already selected. See image below: https://i.stack.imgur.com/SzUgy.jpg <select id="dataPicker" class=" ...

Mapping JSONP responses for jQuery UI autocomplete

Attempting to implement jqueryUI autocomplete. After alerting the response, it shows: ([ { "id": "test", "label": "test", "value": "test" } ]); However, when trying to map the result, the dropdown remains empty. Here is the code being used: <script> ...

Is it possible that bitwise left shifts in JavaScript ES6 (<<) become cyclical after surpassing a shift of 63?

From my understanding of the << bitwise left operator in JS (ES6), the void to the right is typically filled with zeros. However, through observation in both V8 and JSC, it appears that the set bits suddenly reappear when we shift by 64 or more. (2 ...

Retrieve a single document from Firestore and assign it to a variable

While I'm still new to NodeJS, I'm currently working on retrieving a single User document from Firestore. const fs = firebase.firestore(); const usersRef = fs.collection('users'); let findUserByContact = (contact) => { let res ...

Guide on invoking a POST endpoint within another POST API in a Node.js Express server

I encountered an issue while attempting to use fetch in react.js with a backend node.js API URL, which then proceeds to make a POST API call within the server to another route utilizing a different URL. How can I tackle this task effectively? See the code ...

Guide to configuring a function to display the maximum value on a boxplot in Highcharts

I'm currently using Angular in combination with the highcharts boxplot API. While I am aware that I can manually set the max value of the y-axis in the chart configuration, such as: max: 100, tickInterval: 10. There's now a need for me to dynami ...

Encountering difficulties in generating a binary from a nodejs application with pkg

I am having trouble generating a binary executable from my nodejs app using the pkg command. My nodejs app is simple and consists of only three .js files: index.js, xlsx_to_pdf.js, and xlsx_extractor.js. This is how my package.json file looks like: { & ...

Discover the geolocation data for post code 0821 exclusively in Australia using Google Maps Geocoding

I'm having trouble geocoding the Australian postcode 0821. It doesn't seem to reliably identify this postcode as being located within the Northern Territory, unlike 0820 and 0822 which work fine. Here's an example of what I'm doing: ...

Issue: The initiation function fails to start data

I have created an app using Ionic framework that displays articles. When a single article is opened, I use the init function in the UserService to initialize user data: angular.module('coop.services') .factory('UserService', function( ...

What is the best way to include a parameter in the current URL in Django using Paginator?

After setting up a page to display database data, I added a paginator and a search bar to my website. When a user searches for something, the URL changes to include the search query like this: .../search/?q=xyz However, when paginating the search results ...

Is it not possible to utilize async/await with MongoDB Model, despite it yielding a Promise?

Currently, I am facing an issue with a function in my code that is supposed to retrieve a user's inventory and then fetch the price property of each element using data from a Price Collection. Below is a snippet of the function (not the entire thing, ...

How to add a subtle entrance animation to text (demonstration provided)

Apologies for the brevity, but I could really use some assistance with replicating an effect showcased on this particular website: My understanding is that a "fadeIn" can be achieved using jQuery, however, I am at a loss as to how to implement the 3D effe ...

What is the best approach to retrieve a username from a SQL database using AJAX within a Flask application

I have been attempting to retrieve the username column information from SQL using ajax, but only the username of the first ID is being returned. However, I need all usernames to be fetched. Below is the model: class users(db.Model): id=db.Column(db.I ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

Issue with integrating Google Spreadsheet as the data source for a Next.JS website: updates are not reflecting on the website pages

The website for this restaurant was created by me, using Google Spreadsheet to populate the menu pages. I chose this method for its simplicity and familiarity to the client. I'm utilizing the google-spreadsheet package to extract necessary informatio ...

Encountered unexpected character error while parsing JSON data

I am encountering the following error message: JSON.parse: unexpected character when I execute this code in firebug: JSON.parse({"balance":0,"count":0,"time":1323973673061,"firstname":"howard","userId":5383,"localid":1,"freeExpiration":0,"status":fals ...

Guide to transmitting a "token" to an "API" using "React"

As a novice developer, I am facing a challenge. When users log in to our website, a JWT is created. I need to then pass this token to the API on button click. If the backend call is successful, the API response should be displayed. If not, it should show ...