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

skoobi's avatar
Level 13

pagination with collection

Hi. I've got an issue when trying to paginate a collection, but as its a collection there is no paginate.

I need to sort the data in a way that it orders it correctly and grabs the first in the group rather than show all the scans, is there a way I can put it into one so I can paginate ?

    $collection = CustomerScan::where('user_id', Auth::user()->id)
            ->orderByRaw('CAST(created_at AS DATE) DESC') // order by future grouped by
            ->orderBy('group_id') // order within each group
            ->orderBy('order') // order within each group
            ->paginate(9);

        $scans = $collection->groupBy('group_id')->map(function ( $scans ) {
            return collect($scans)->first();
        });

Many thanks

0 likes
5 replies
Tray2's avatar

Why are you maping over your collection?

siangboon's avatar

since you already use orderByRaw, it may easier by simply merging with the group_id and order together in the raw statement

skoobi's avatar
Level 13

@tray2 Mapping over to grab the first item in a group. I don't want to show all of the images only the first image of a group.

@siangboon Thanks i'll give that a try

Tray2's avatar

Then pull it in a seperate query instead.

skoobi's avatar
Level 13

Sorry been a while since I was on this issue. Now i'm back on it.

In what sense do you mean put it in another query? Im not too good on the eloquent side but trying to learn.

This is what I have at the moment, but the map function is causing the issues.


$collection = CustomerScan::where('user_id', Auth::user()->id)
            ->orderByRaw('CAST(created_at AS DATE) DESC') // order by future grouped by
            ->orderBy('group_id') // order within each group
            ->orderBy('order')
            ->paginate($this->perPage);

$scans = $collection->groupBy('group_id')->map(function ( $scans ) {
    return collect($scans)->first();
});

return view('livewire.scan-viewer.show-all-scans')->with(['scans' => $collection]);

View

@foreach($scans as $scan)

    <x-scan-viewer-index-card :scan="$scan"></x-scan-viewer-index-card>

 @endforeach

Please or to participate in this conversation.