dr24's avatar
Level 2

How to get all results (from all pages) in pagination in Laravel?

I have query that returns users with some data from search. Currently I get only users from first page, but I need to get all users from all pages. I am having trouble solving this with current setup.

0 likes
6 replies
LaryAI's avatar
Level 58

To get all results from all pages in Laravel pagination, you can use the simplePaginate method instead of paginate method. The simplePaginate method returns a paginator instance that only includes the "next" and "previous" links, while the paginate method returns a paginator instance that includes links to all pages.

Here's how you can modify the search method in SearchService.php to use simplePaginate method:

public function search(Request $request)
{
    $page = $request->get('page', 1);
    $queries = $request->all();
    $perPage = 20;
    $results = $this->repository->search($queries, $perPage, $page);

    $allResults = collect($results['results']);

    while ($results['next_page_url']) {
        $nextResults = $this->repository->search($queries, $perPage, ++$page);
        $allResults = $allResults->merge($nextResults['results']);
        $results = $nextResults;
    }

    dd($allResults); // HERE YOU WILL GET ALL RESULTS FROM ALL PAGES

    if ($request->user_distance_in_km) {
        $distanceUsers = $this->findNearestUsers($authUser->latitude, $authUser->longitude, $request->user_distance_in_km)->pluck('id');

        $query = $allResults->whereIn('id', $distanceUsers);

        $users = new LengthAwarePaginator($query, $allResults->count(), $perPage, $page);

        return response()->json([
            'users' => $users,
        ]);
    }
}

In this modified search method, we first get the results from the first page using the paginate method. Then, we create a new collection $allResults and add the results from the first page to it using the collect method. We then use a while loop to get the results from all the remaining pages using the next_page_url property of the paginator instance. We merge the results from each page to the $allResults collection using the merge method. Finally, we return the $allResults collection.

Note that we have also modified the code that filters the results based on user distance to use the $allResults collection instead of the $results['results'] collection. We have also modified the LengthAwarePaginator constructor to use the $allResults->count() method instead of $results['total'] to get the total number of results.

1 like
sirhxalot's avatar

@dr24 Can you please shaare the UserRepository->search() method aswell? But for now please try to set $perPage to false this may do the trick.

dr24's avatar
Level 2

@sirhxalot false says 'Division by zero' and -1 return only users from first page.

Please or to participate in this conversation.