1 year ago

Get the Collection behind a Paginator object

Posted 1 year ago by FrenchFryNinja

I have a pagination object and need to offer the user the ability to download the collection and its associated objects.

Without redoing the query, is there a way to access the LengthAwarePAginator's underlying collection in order to pass it to a method?

For example:

//Complex and time consuming query sets $orderIds
$results = Order::whereIn('id', $orderIds)->paginate(10);
//something like this:
$underlyingCollection = $results->toCollection();

And now I want to be able to call:


and be able to access the collection behind the $results object so that I do not have to repeat a time consuming query.

I imagine that the best way it probably to extend LengthAwarePaginator with a custom implementation that will iterate over all pages like this, but all I'm getting is the first collection repeated over the total size of the initial Collection that built the Paginator:

public class MyLengthAwarePaginator extends LengthAwarePaginator

public function toCollection()
    $results = new Collection();
    $start = $this->currentPage;
    while ( $start++ <= $this->lastPage()) {
        foreach ($this->getCollection() as $item) {
        $this->setCurrentPage($start, $this->pageName);
    return $results;


Please help. I know I'm missing a fundamental understanding of something here.

Please sign in or create an account to participate in this conversation.