Implementing Laravel pagination to retrieve data through ajax calls

I am currently working on setting up a pagination feature using Laravel. When it comes to the backend, I have set up my JSON response in the following way:

        if(isset($request->myDate)) {

            $request->validate([
                'myDate'  => 'required|date',
            ]);

            $start_date = $request->get('myDate');
            $end_date = Carbon::now();

            $my_tickets = Ticket::where('admin_id', Auth::user()->id)->whereBetween('updated_at', [$start_date, $end_date])->with(['getAdmin'])->paginate(10);

    }   

    return json_encode($my_tickets);

As for the frontend part, I'm utilizing AJAX requests to show the rows. My main query now is how do I integrate the pagination system? Are there any built-in features in Laravel or external components that can simplify this task? Do I need to develop the front end myself since I cannot utilize the $var->links() function as when returning a view?

Warm Regards

Answer №1

When working with the frontend Response, you have access to valuable information such as the page number, total count, and items per page. If you are looking to implement custom ajax pagination, consider using the code snippet below in your ajax calls.

  var page = ''
                    var count = 0;
                    if (response.total > response.perPage) {
                        if (response.page != 1) {
                            page += '<li class="page-item"><a class="page-link" data-page="' + (response.page - 1) + '" href="#">' + 'Previous' + '</a></li>'
                        }
                        for (i = response.page; i <= response.totalPage; i++) {
                            count++;

                            if (response.page == i) {
                                page += '<li class="page-item active"><a class="page-link" data-page="' + i + '" href="#">' + i + '</a></li>'
                            } else {
                                page += '<li class="page-item"><a class="page-link" data-page="' + i + '" href="#">' + i + '</a></li>'
                            }

                            if (count == 10) break;
                        }
                        $('.number-of-show').append(' Showing ' + ((response.perPage * (response.page - 1)) + 1) + ' to ' + response.perPage * response.page + ' of ' + response.total);
                        $('.pagination').append(page);
                    }

Within the controller:

   $page = '';
        if (!empty($data['page'])) {
            $page = $data['page'];
        }
        $params['totalPages'] = ceil($paramsData['total'] / $params['perPage']);
        $params['offset'] = ($page - 1) * $params['perPage'];

        $withdrawRequestLists = $paramsData['data'];
        $total = $paramsData['total'];
        $totalPage = ceil($total / $params['perPage']);

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

Can you incorporate personalized icons in ReactJS?

Is there a way to incorporate my personally designed custom icons, available in both SVG and TTF formats, into a React project? I am interested in using these icons in my navigation bar, such as creating a unique home icon for the home button. ...

How to Query MongoDB and reference an object's properties

I'm trying to execute a script on my MongoDB that will set teacher_ids[] = [document.owner_id]. The field owner_id already exists in all the objects in the collection. Here is my current attempt: db.getCollection('readings').update({ $where ...

Issue with MaterialUI value prop not updating after dynamic rendering of components when value state changes

As I dynamically generate Material UI form components, I encounter an issue with updating their values. The value prop is assigned to a useState values object, and when I update this object and the state, the value in the object changes correctly but the M ...

Tips on increasing video size upon visiting a website. HTML, JavaScript, and potentially jQuery can be used for video animation

Is there a way to create a video pop-up in the same window when visiting a website? I want the video to increase in height from 0 to a specific height and move slightly upwards. Are there JavaScript or jQuery functions that can achieve this effect? I wou ...

The event listener attached to this model is failing to trigger when there are

The issue is that the "change" event is not being triggered in the code snippet below. var PageView = Backbone.View.extend({ el: $("body"), initialize: function(){ this.model.on("change:loading", this.loader, this); }, loader: func ...

Design a div in the shape of a trapezium with clipped overflow

Is there a way to create a trapezium using CSS/Html/Canvas? I have attempted to do so, but my current method is messy and not practical. div { width:0; margin-left:-1000px; height:100px; border-right:1000px solid lightblue; border-top:60px solid tra ...

How to effectively trigger a function to load images in React

When my react app loads, I want the images to load immediately. This involves calling the function collectionChanged(e.target.value) on application start. Inside a .jsx file, there is a function named getHomePage() which contains 4 functions. Upon calling ...

Is there a way for me to show "No data" when the json response in vue js is empty?

Is it possible to display a message like "No search results" when there is no data available? I am new to this and only have basic understanding. Can someone guide me on how to achieve this? Example of my JSON data when it's empty: { "status": true ...

Checking if the group of radio buttons has been selected using JQUERY

Need help with validating a group of radio buttons. If none are checked, display an error message in the span element to prompt users to select an option. The strange issue I am facing is that the validation code works only when placed below the radio butt ...

Is there a way to inform Laravel that only the user who owns a particular thread is allowed to edit or delete it?

I have a new project where I am building a website to learn the Laravel framework. The website includes features like login/register, creating threads, and editing/deleting threads. However, I am facing an issue where any logged-in user can edit or delete ...

React Native - The size of the placeholder dictates the height of a multiline input box

Issue: I am facing a problem with my text input. The placeholder can hold a maximum of 2000 characters, but when the user starts typing, the height of the text input does not automatically shrink back down. It seems like the height of the multiline text ...

There was an unexpected token syntax error while trying to assign the database URL from the environment variable "REACT_APP

I am facing an issue with setting an environment variable in my mongo.js file. Here is the code snippet where I have set the ENV variable: const mongo = require('mongodb').MongoClient; const assert = require('assert'); const ObjectId = ...

What could be the issue with trying to bind an event handler in this manner?

I'm having some trouble binding an event handler with jQuery: $(document).ready(function () { var newsScrollerForPage = new NewsScroller(); newsScrollerForPage.init(); $('#scroller-left-a').bind('on ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...

What is the process for including the Authorization HTTP header in a JSONP request?

I am attempting to make a GET request to the Yelp API. When I use the code below, I encounter a 401 error. From my research, it seems that setting the authorization in this manner is not possible when requesting JSONP data. However, when I attempt another ...

Creating a route-guard in a Vue.js/Firebase authentication system for secure navigation

I have created a Vue.js/Firebase authentication interface following a tutorial. The app is mostly functioning properly, but I am experiencing issues with the route guard. Upon signing in and redirecting from "http://localhost:8080/home" to "http://localh ...

The connection could not be established due to a cURL error 6: The host "local.crm.test.com" could

Encountering a problem shown in the screenshot specifically on my Laravel setup on my local system, utilizing a Docker container for this project. ...

The presence of a backslash is preventing the state from transitioning to '/{username:[a-zA-Z0-9]{3,20}}' within the AngularJs UI-router

In my abstract root state named 'site', the empty URL ('') contains two child states: 'profile' and 'home'. The URL for home is '/', while the URL for profile is '/{username:[a-zA-Z0-9]{3,20}}'. I ...

Steps to resolve the issue: The 'jsx' functionality is not activated at the moment

I recently started working with ReactJS and I came across a similar error message in this post: Syntax Error: Support for the experimental syntax 'jsx' isn't currently enabled. Despite reading it, I am still unable to solve my issue. When I ...

Tips for efficiently serving a static file without triggering a disk read

res.sendFile is the preferred method for serving a static file in express. However, it appears that res.sendFile reads the file from disk with each request, as shown below: router.get('/', (req, res) => { res.sendFile('./guest.js&apo ...