0

I use paginate in Laravel to load a large amount of data. Data that changes quickly. The problem is that as the user scrolls through the data, new rows are being inserted at the top. This creates an issue where the user sees a duplicate row that got pushed out of page 1 into page 2 in the time between the user loading page 1 and page 2. For example:

Data:

  1. D
  2. E
  3. F

User A loads results using ->simplePaginate(2).

Page #1 loads:

Results:

  1. D
  2. E

inserts a row into the database.

Data:

  1. C
  2. D
  3. E
  4. F

User A now scrolls past his results on page #1 and page #2 loads:

Results:

  1. E
  2. F

User A now just saw:

  1. D
  2. E
  3. E <-- error
  4. F

Is there a way I can easily account for this when loading the second page?

User A should have seen

  1. D
  2. E
  3. F

It would also be super cool to pass along some information when User A loads page #2 saying "Hey, there are new results at the top now."

1 Answers1

1

Take a timestamp on page 1, and then add an additional clause to the query, asserting that created_at is before the timestamp.

$beforeTime = $request->input('before_time', Carbon::now());
$items = Item::where('created_at', '<=', $beforeTime)->paginate(2);

Lastly, make sure to append the before_time parameter to the pagination links:

echo $items->appends(['before_time' => $beforeTime])->links();
levi
  • 23,693
  • 18
  • 59
  • 73