azimidev's avatar

Pagination with filter helper

Does anyone know how to add pagination for this query where I'm using laravel filter helper function

$matches = User::where('gender', auth()->user()->looking_gender)
   ->ageBetween(
        auth()->user()->looking_age_from,
        auth()->user()->looking_age_to
    )
   ->visible()
   ->confirmed()
   ->notBlocked()
   ->latest()
   ->get()
   ->filter(function ($user) {
       return matrix(
            $user->location, 
            auth()->user()->location, 
            auth()->user()->looking_distance
        );
   }); // TODO add pagination
0 likes
3 replies
azimidev's avatar

I know how to paginate the collection but filter doesn't work with paginate(20) it needs get() before filter or pagination links wont work.

Thx

azimidev's avatar
azimidev
OP
Best Answer
Level 55

Got it! I built a custom paginator helper for my collection [not array] like this:

function custom_paginate($items, $perPage)
{
    $pageStart           = request('page', 1);
    $offSet              = ($pageStart * $perPage) - $perPage;
    $itemsForCurrentPage = $items->slice($offSet, $perPage);

    return new Illuminate\Pagination\LengthAwarePaginator(
        $itemsForCurrentPage, $items->count(), $perPage,
        Illuminate\Pagination\Paginator::resolveCurrentPage(),
        ['path' => Illuminate\Pagination\Paginator::resolveCurrentPath()]
    );
}

Then I used this for my collection like this:

$matches = User::where('gender', auth()->user()->looking_gender)
   ->ageBetween(
        auth()->user()->looking_age_from,
        auth()->user()->looking_age_to
    )
   ->visible()
   ->confirmed()
   ->notBlocked()
   ->latest()
   ->get()
   ->filter(function ($user) {
       return matrix(
            $user->location, 
            auth()->user()->location, 
            auth()->user()->looking_distance
        );
   });

$matches = custom_paginate($matches, 20);

Please or to participate in this conversation.