Laravel and Vue: tackling pagination issues in a Vue.js and Laravel application

I'm struggling with getting Laravel pagination to function properly. Although I attempt to access results from different pages, I find that I can only retrieve the first page. Even when I click on page 2, upon checking the request payload, it always indicates that it's still on page one. Moreover, when I select the button for page two, it briefly highlights as active before reverting back to the first button being active.

Below is my pagination component:

<template>
<nav class="LAYOUTpagination1_maincontainer container">
    <button class="LAYOUTpagination1_link c_dark fs_normal link" type="button" @click.prevent="changePage(1)" :class="{ 'disabled' : pagination.current_page <= 1 }">
        <i class="fas fa-angle-double-left"></i>
    </button>
    <button class="LAYOUTpagination1_link c_dark fs_normal link" type="button" @click.prevent="changePage(pagination.current_page - 1)" :class="{ 'disabled' : pagination.current_page <= 1 }">
        <i class="fas fa-angle-left"></i>
    </button>
    <a class="LAYOUTpagination1_link c_dark fs_normal semi_bold link" type="button" @click.prevent="changePage(page)" v-for="(page, index) in pages" :key="index" :class="isCurrentPage(page) ? 'LAYOUTpagination1_active' : ''" >{{ page }}</a>
    <button class="LAYOUTpagination1_link c_dark fs_normal link" type="button" @click.prevent="changePage(pagination.current_page + 1)" :class="{ 'disabled' : pagination.current_page >= pagination.last_page }">
        <i class="fas fa-angle-right"></i>
    </button>
    <button class="LAYOUTpagination1_link c_dark fs_normal link" type="button" @click.prevent="changePage(pagination.last_page)" :class="{ 'disabled' : pagination.current_page >= pagination.last_page }">
        <i class="fas fa-angle-double-right"></i>
    </button>
</nav>
</template>
<script>
export default {
name:'LAYOUTpagination1',



computed: {
    pages() {
        let pages = [];
        let from = this.pagination.current_page - Math.floor(this.offset / 2);
        if (from < 1) {
            from = 1;
        }
        let to = from + this.offset - 1;
        if (to > this.pagination.last_page) {
            to = this.pagination.last_page;
        }
        while (from <= to) {
            pages.push(from);
            from++;
        }
        return pages;
    }
},


props:
{
    pagination: { required:true },
    offset: { default:4, type:Number },
},


methods:
{
    isCurrentPage: function(page) {
        return this.pagination.current_page === page;
    },
   
   
    changePage: function(page)
    {
        if (page > this.pagination.last_page)
        {
            page = this.pagination.last_page;
        }
        this.pagination.current_page = page;
        this.$emit('paginate',page);
    }
}


}
</script>

Here is my other component where I retrieve results:

<layout-pagination-1 v-if="pagination && pagination.last_page > 1" :pagination="pagination" @paginate="onGetPostsAndCategoriesPaginated"></layout-pagination-1>

methods:
{

    handlePagination(pagination)
    {
        
        this.pagination = pagination;
        this.page = pagination.current_page;
        this.numberOfPages = pagination.last_page;
        
    },



    async onGetPostsAndCategoriesPaginated()
    {
        
        this.loader = 0;
        
        try 
        {
           console.log('pagination',this.pagination);
           this.loader = 1;
            let params = { page:this.page, paginate:this.paginate };
            let response = await axios.get('/api/posts/get-posts-and-categories', { params: params });
            this.loader = 2;
            console.log(response.data.posts);
            this.posts = response.data.data.data;
            this.handlePagination(response.data.pagination);
            console.log(this.posts);
        } 
        catch (error) 
        {
            this.loader = 3;
            throw error;
        }
        
        
    },
}

Your help is greatly appreciated.

Answer №1

Why make your life more complicated when you can easily use a pre-existing package for it?

Check out this Laravel Vue Pagination package

If you prefer to create your own solution, I recommend installing this package and studying how the pagination feature works. I personally found this solution to be very comprehensive and well-thought-out.

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 modify a nested object in MongoDB based on the JSON data provided

In my possession, there exists a structured form of JSON data as displayed below: [ {"size":100,"year":2015,"geography":"London","age":"21","gender":"Female"}, {"size":80,"year":2015,"geography":"Cardiff","age":"38","gender":"Male"}, {"size":80,"year":201 ...

What is the best way to increment the stock number based on the quantity of items in the cart using Next.js

I am in the process of developing a shop system where customers can order items and save them to the database. I have encountered an issue where I need to calculate the remaining stock after deducting the quantity of items ordered. My API is responsible f ...

The issue of Jquery selectors not functioning properly when used with variables

Currently working on a script in the console that aims to extract and display the user's chat nickname. Initially, we will attempt to achieve this by copying and pasting paths: We inspect the user's name in the Chrome console and copy its selec ...

Sending information from a Vuex module to a component following an axios request

I'm currently working on developing a Vue.js based application. Here's the scenario I'm facing: I have a component with a popup where users can create an 'expense' entry. Upon clicking the 'save' button, a function in the ...

Wrapping header text in Vuetify's v-data-table

Struggling with wrapping the header text on a v-data-table component. I've tried applying styles, but only tbody elements are affected. The header (thead element) remains unchanged. Any suggestions on how to get custom styling for the header? For ins ...

What is the best way to determine if any of the list items (li's) have been marked as selected?

<div id='identifier'> <ul id='list'> <li id='1' class="">a</li> <li id='2' class="">a</li> <li id='3' class="">a</li> <li id='4' class=" ...

Sending all form input data to Ajax for GET request

Today, my goal is to iterate through each textbox with an ID of setting_value, set its name and value to a key-value array, and then send that data in an Ajax request. The problem I'm facing is that it only seems to be inspecting the first instance o ...

Having trouble retrieving a value within the jQuery.ajax success function

I need to implement jQuery Validator in order to validate if a user's desired username is available during the sign-up process. The PHP script untaken.php is responsible for checking this, returning either ok if the username is free or taken if it is ...

Tips for concealing broken images in jQuery/JavaScript when generating dynamic content

Is there a way to hide the broken images in this dynamically generated HTML code using JavaScript? Unfortunately, I don't have access to the source code itself. I'm new to JQuery and could really use some assistance. Below is the snippet of the ...

Showing a React Portal Toolbar only when populated with children

OBJECTIVE: The objective is to show the ToolkitArea only when there are children present in "#toolkitArea". CHALLENGE: Unable to accurately determine the number of children inside the ToolkitArea. ACTIONS TAKEN SO FAR: I have developed a component calle ...

Contrasting the Javascript onload event with plain script within an html page

Can you identify the distinction between these two code snippets: Sample 1: <script type="text/javascript> function myfunc () { alert('hi'); } window.onload = myfunc; </script> Sample 2: & ...

Should we avoid using 'RedirectToAction' with AJAX POST requests in ASP.NET?

As a newcomer to jQuery, Json, and Ajax, I am putting in the effort to grasp the concepts clearly, but I am facing some difficulties. I have an ajax POST Delete method that is currently functional, however, my professor has suggested that I refactor the c ...

What causes Vue to drop nested component data within a v-for loop?

Witness the mysterious behavior through my fiddles: Anticipated outcome: https://jsfiddle.net/o7c9mwzf/27/ By clicking "unshift," I add an element to the beginning of my items array. After setting its data, clicking "unshift" again should maintain the el ...

What could be causing the lack of updates in my shared service across all components?

I have implemented an Angular2 app where I am initializing an authentication service called LocalStorage which I want to be accessible across all my components: bootstrap(AppComponent, [ ROUTER_PROVIDERS, LocalStorage ]); The definition of the Lo ...

Utilizing dynamic jQuery events with variable integration

I'm having some trouble incorporating a variable into a dynamically added jQuery event. Every time I click, the message displayed is "The number is 3" for all div elements. $( document ).ready(function() { for (var i = 0; i < 3; i++) { ...

Ajax appends a single row, not an entire array

My ajax function is retrieving an array of data from the backend, but when I try to display it in the blade, only one row appears instead of multiple rows. List of Problems Only 1 row is appended by ajax The select option is empty when the results return, ...

Determine the index of a specific character within a string using a "for of" loop

How can I obtain the position of a character in a string when it has been separated programmatically using a for...of loop? For instance, if I wish to display the position of each character in a string with the following loop: for (let c of myString) { ...

Despite being invoked five times and enclosed in a React.Fragment tag, the functional component is still not displaying any content

<html lang="en"> <head> <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js& ...

ngx-slick-carousel: a carousel that loops infinitely and adjusts responsively

I have implemented ngx-slick-carousel to showcase YouTube videos in my project. However, I am facing two main issues. Firstly, the carousel is not infinite, and when the last video is reached, there appears to be white spaces before it loops back to the fi ...

Getting an input value dynamically in a React variable when there is a change in the input field

I am having an issue with my search text box. I need to extract the value onchange and send a request to an API, but when I try using the normal event.target method, it shows an error. How can I fix this? The problem is that onchange, I need to call a func ...