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

fredmarks's avatar

Update/Recalculate pagination after dropping some items from collection

I am currently pulling some rows from my database, which I then do some addition logic on (I cannot do the logic directly when pulling the rows)

       foreach ($items as $key => $item) {
                 if($item->foo == 'bar'){
                        $items->forget($key);
                }
           }

I then use the pagination in my view response

if ($item->currentPage() < $items->lastPage()) {
     //show load more button
}

This works fine, but if I forget() some rows, the pagination becomes incorrect. How can I recalculate the pagination so that its correct, after my routine above

0 likes
2 replies
bobbybouwmann's avatar

You have to first filter out all the results you don't want using forget. After that, you need to paginate manually. You can't use the Laravel default query paginator since that is working based on the query and not the results you removed from it.

You can create your own pagination object like so

$users = Item::all();

$page = $request->input('page', 1); // Get the ?page=1 from the url
$perPage = 15; // Number of items per page
$offset = ($page * $perPage) - $perPage;

return new LengthAwarePaginator(
    array_slice($users->toArray(), $offset, $perPage, true), // Only grab the items we need
    count($users), // Total items
    $perPage, // Items per page
    $page, // Current page
);

This should make your query work as well ;)

Snapey's avatar

Adjust your query so that the items are not retrieved from the database in the first place rather than dropping them from the collection.

Please or to participate in this conversation.