Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pdellepiane's avatar

Get Query Information before Pagination

Hello,

I'm trying to get a few counts on my full ORM query before doing the pagination because it breaks the total results and I need the whole results to make some calculations. Here is part of the code I'm trying to deal with:

// Here I get the filtered users by type and situation and paginate the result
$users = User::where('type',$type)->where('situation',$situation)->paginate(20, ['*'], 'page', $request -> page);

// Because I need the whole results and not the paginated to count the stars I need to retrieve the filtered users again
$users_temp = User::where('type',$type)->where('situation',$situation)->get();

$users -> total_one_stars       = $users_temp->where('stars',1)->count();
$users -> total_two_stars       = $users_temp->where('stars',2)->count();
$users -> total_three_stars     = $users_temp->where('stars',3)->count();
$users -> total_four_stars      = $users_temp->where('stars',4)->count();
$users -> total_five_stars      = $users_temp->where('stars',5)->count();

return new UserResourceCollection($users);

How do I do it without having to call the filtered Users again?

Thanks in advance.

0 likes
3 replies
pdellepiane's avatar

@snapey I agree with what you say, its not very scalable, but its worse to call the query twice. Is there a way to play with the results and then ask for pagination?

Btw, thanks for the link, I'll apply it for sure.

Snapey's avatar

No, You will always need two queries

Please or to participate in this conversation.