mrkarma4ya's avatar

Limit and paginate

Lets say I have a table users with 1000 records. I want to get the latest 100 users, but paginate them by 10 each. I tried both Users::latest()->take(100)->paginate(10) and Users::latest()->limit(100)->paginate(10) , but they didn't work as expected.

I wanted the pagination to have 10 pages total (100 users) but it still gives 100 total pages.

0 likes
4 replies
MichalOravec's avatar

This is not possible in query builder or eloquent. The only solution what I know is to paginate the collection.

$preparation = Users::latest()->take(100)->get();

$users = $preparetion->paginate(10);

You can create a paginate macro for a collection:

https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e

And of course don't forget to you cache at least for preparation result.

Snapey's avatar

I had a similar situation recently and decided to paginate only the records created in the last 14 days, which was a valid constraint in my case

you could try an additional query to get the id of the 100th record from the end and then use that id as a constraint on the paginator

$user100 = User::select('id')->take(100)->latest()->last()->id;

$users = User::where('id','>=',$user100)->paginate(10);
1 like
Muttaqi's avatar

@Snapey Thanks a lot legend. I tried so hard on this for the last few hours. Finally the solution!

Please or to participate in this conversation.