Level 24
You are trying to paginate a collection right?
https://laracasts.com/discuss/channels/eloquent/paginate-eloquent-collection
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
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.