brandymedia's avatar

Laravel pagination duplicating data

I'm using Laravel's pagination to display a list of follows using the below code:

Follow::where('user_id', $user->id)->orderBy('created_at', 'desc')->paginate(10)->fragment('audience');

However, I keep noticing duplicate entires across multiple pages?

I've taken a look at the data in the database and there are not duplicated entries in there.

If I remove the orderBy clause, the issue seems to go away...?

Has anyone else experienced this, it is most odd.

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

When ordering by a column that might have duplicates, you always need to add a fallback

->orderByDesc('created_at')
->orderBy('id')

This will ensure that the data is "stable" between pages

2 likes
brandymedia's avatar

@Sinnbeck thank you.

That was it. There are multiple entires sharing the same created_at timestamp.

Thanks again, I've learnt something new today 👍

Please or to participate in this conversation.