angelsky's avatar

Pagination from merge()

Hello,

I've merges 2 Collections:

use Illuminate\Pagination\LengthAwarePaginator as Paginator;

...

$towni18n = TownI18n::where(...)->get();
$town = Town::where(...)->get();
$all = $towni18n->merge($town);

$perPage = 10;
$input = \Input::all();
if (isset($input['page']) && !empty($input['page'])) { $currentPage = $input['page']; } else { $currentPage = 1; }

$paginator = new Paginator($all, $all->count(), $perPage, $currentPage);
return $paginator;

The output is not following the pagation but returns all the results:

{
total: 547,
per_page: 10,
current_page: 1,
last_page: 55,
next_page_url: "/?page=2",
prev_page_url: null,
from: 1,
to: 547,
data: [
{
id: 1423550,
[...]

Any idea how to fix this ?

0 likes
1 reply
angelsky's avatar
angelsky
OP
Best Answer
Level 3

It seems that you have to slice manually. From the Laravel 5.1 doc:

"When manually creating a paginator instance, you should manually "slice" the array of results you pass to the paginator."

So the answer is:

$arr = $all->toArray();
$offset = ($currentPage * $perPage) - $perPage;
$arr_splice = array_slice($arr, $offset, $perPage, true);
$paginator = new Paginator($arr_splice, count($arr), $perPage, $currentPage);

More infos on https://laracasts.com/discuss/channels/laravel/laravel-pagination-not-working-with-array-instead-of-collection?page=1

Please or to participate in this conversation.