What is the most effective way to retrieve comments using Laravel Pagination without duplicates?

Lingering Issue:

In the scenario where a user leaves a comment and subsequently opts to load more comments, they may encounter at least one duplicate comment.

Root Cause:

Using Laravel Pagination, the script leverages Axios to fetch the last 10 items. Upon adding a comment and fetching the next set of 10 items, the order shifts by one element, resulting in a repeated item.


Attempts to Resolve:

Initial Approach: I attempted utilizing Array.prototype.includes() or Lodash Includes:

 data(){
    return { items: [] };
 }
 ...
 addWithoutRedudancy(newItems){
    for(let item of newItems){
        if( ! _.includes( this.items, item ) ) this.items.push(item);
    }
 }

Challenges Faced:

  1. Even with seemingly identical objects, when comparing $vm0.items[10] == $vm0.items[11], it returns false despite looking similar and having the same properties. This inconsistency hinders the detection of redundant objects. It's unclear why these objects are stored differently; perhaps due to asynchronous fetching via axios on different timings?

  2. Furthermore, even if addressed, after a user posts 8 new comments, only 2 new comments are returned from pagination (controller), instead of the expected 10 following comments.

Alternate Attempt

/**
 * Fetch all relevant comments.
 *
 * @param string $username
 * @param Selllink $selllink
 */
public function index($username, $selllink)
{
    //Route::prefix('/{username}/{selllink}
    //Sellink gets the model of sell and loads all comments to that sell.
    //get me the latest first (we want to see the current comments)
    //take only 10 coments with paginatation

    return $selllink->sell->comments()
                ->latest()
                ->offset($addedCommentsNumber??) //that can't work...
                ->paginate(10);
}

Challenges Persist: Offsetting the entire table isn't feasible. The goal is to offset paginated comments and incorporate the missing comments.


Resolution Needed

There must be a more efficient solution to address this issue, but the best approach remains elusive.


Additional Explanation (if required):

Utilizing a Vue Comment Component, I retrieve data from my CommentController employing Pagination:

methods: {
        fetch(){
            axios.get(this.url()).then(this.refresh);
        },
        url() {
            this.page++;
            return `${location.pathname}/comments?page=${this.page}`;
        },
        refresh({data}){
            this.dataSet = data;
            this.addWithoutRedudancy(data.data);
        },
}

To access additional comments, users simply click the "load more" button triggering the retrieval of additional comments

Answer №1

Big shoutout to @James for the help. Managed to save the latest ID of all fetched Comments and implemented a WHERE Query.

Updated my Vue Method to:

url() {
    this.page++;
    return `${location.pathname}/comments?page=${this.page}&lastComment=${this.idOfLastComment}`;
},

Modified my Controller as follows:

/**
 * Retrieve all relevant comments.
 *
 * @param string $username
 * @param Selllink $selllink
 */
public function index($username, $selllink)
{
    $commentID = request('lastComment', $default = 0);
    $filter = $commentID == 0 ? '>' : '<=';

    return $selllink->sell->comments()
                ->where('id', $filter, $commentID)
                ->latest()
                ->paginate(10);
}

Everything is running smoothly now :)

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

Emailer: Missing Salutation

While attempting to send emails using Node with Nodemailer (https://github.com/nodemailer/nodemailer), the sendMail call from the Nodemailer transporter is throwing an error message of Greeting never received when connected to an Ethereal test email accoun ...

Unable to retrieve the field value from the Json Object

I have a JSON object that I need to parse and display in a data table, but I'm having trouble reading the contents of the object. Here is my JavaScript function: finalGrid: function(data){ console.log("Final Grid"); var strJson = JSON.strin ...

The modal remains visible

Has anyone encountered a problem with hiding a Bootstrap modal based on form validation in JavaScript? I'm facing an issue where the submit function is not executed when I click the button. I've attempted using onsubmit=validateForm(), but it doe ...

How to efficiently highlight a row in a table when hovering over one of its cells, utilizing the React hook useState

I have a table displaying a list with three columns: item, delete-button-1, delete-button-2. When hovering over a delete button, the corresponding item is highlighted in red. Utilizing React Hook useState to store the index of the row where the delete bu ...

Dragging a Google Maps marker causes a border to appear around a nearby marker

Recently, I added a main draggable marker to the map. However, an unusual issue arises when dragging this marker - a blue outline appears around one of the existing markers on the map. This behavior is puzzling as it seems to be triggered by a click event ...

Receiving multiple NodeJS Responses through AJAX for a single request

I have been working on a WebApp that involves heavy AJAX calls from the frontend and NodeJS Express at the backend. Here is a glimpse of my Frontend Code- Below is the global AJAX function I consistently use in all my projects: function _ajax(params = {}, ...

What is the proper way to place the authorization header for a background image using the url()

I am currently working on fetching background images through a REST API. However, in order to successfully retrieve these images, I have to go through an authorization process. The token required for authorization is already present in the context where ...

Limiting the maximum date for a datepicker

Looking to customize my datepicker code so that maxDate is only applied when selector === '#Birth'. Any suggestions on how to accomplish this? function customdatepicker(selector) { $(selector).datepicker({ inline: true, showO ...

Reading a glTF file from the local system onto Javascript's memory

Currently, I am working on developing a native iOS and Android application using three.js and Capacitor. One of the challenges I am facing is loading GLTF models from an asset folder that is bundled with the code and delivered to the user. I am unsure abou ...

The form data for a Laravel Vue.js/Axios PUT request is coming through as empty

I am facing an issue with sending data using axios. When I use a post request to send formdata, the data is successfully sent to the API. However, when I switch to using a put request, it seems that formData is not being properly handled. <template> ...

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...

Enhancing Next.js Images with Custom CSS Styles

I am working with a Next.js component: import styles from '../styles/Navbar.module.css' import Image from 'next/image' export const Navbar = () => { <div> <Image className={styles["navbar-home-icon"]} ...

Successfully updating a document with Mongoose findByIdAndUpdate results in an error being returned

findByIdAndUpdate() function in my code successfully updates a document, but unexpectedly returns an error that I am having trouble understanding. Below is the schema that I am working with: const userSchema = mongoose.Schema({ phone: String, pas ...

The type 'Node' does not have the required attributes

Could anyone shed some light on what might be causing the issue described below? Your insights are greatly appreciated. The problem lies within the line of code: clone = thead.cloneNode(true); The error message reads: 'Type 'Node' is missin ...

Vue project encountering issue with displayed image being bound

I am facing an issue with a component that is supposed to display an image: <template> <div> <img :src="image" /> </div> </template> <script> export default { name: 'MyComponent', ...

Error: Unhandled Exception - Invalid syntax, unrecognized value: #

Encountering an error in jQuery with a .click() event, as seen in Firebug. Using the latest version 1.3.2 (min), the click triggers an $.ajax() request for a form on my website. Researching online, found information on "%" or "[@]" as unrecognized expressi ...

The functionality of the JavaScript array filter appears to be functioning properly; however, it does not display any output on

As the array (2001, 1999, 2000 and 2002) grows by 4 years The array is displayed on the screen, featuring the same 4 years It's determined that the highest year is 2002 2002 is then removed from the array The array is again shown on the screen with al ...

Is there a jQuery alternative to XMLHttpRequest's upload functionality?

When working with the HTML5 File API, the upload process is handled through an object called upload within the XMLHttpRequest. I am currently following a tutorial on this topic, you can find it here (or use the Google cache mirror since the original link i ...

Unable to leverage the most recent iteration of three js

Having trouble using the newest version of three.js (r102) in IE. I keep getting an ImageBitMap error (ImageBitMap is not defined). Any tips on how to solve this would be greatly appreciated. Thanks! ...

Using both a button and a link simultaneously in react is not possible

I have a single page app that consists of 4 different components, each of them requiring a submit button to save and send data within the form. However, I am facing an issue where using the submit button only submits the information, but I also need to in ...