nztim's avatar

Manual pagination links (5.0/5.1)

I'm updating a L4 application to L5 which uses manual pagination and I'm trying to understand how the links work. I wrote this simple but rough example to illustrate:

Route::get('events/category', function(Illuminate\Http\Request $request) {
    $array = [];
    for($i = 0; $i < 100; $i++) {
        $array[] = "Item#{$i}";
    }
    // 
    $perPage = 10;
    $currentPage = 1;
    if ($request->has('page')) {
        $currentPage = (int) $request->get('page');
    }
    $events = collect($array);
    $items = $events->slice(($currentPage - 1) * $perPage, $perPage)->all();
    $paginated = new Illuminate\Pagination\LengthAwarePaginator($items, $events->count(), $perPage, $currentPage);
    $content = var_export($paginated);
    $content .= $paginated->setPath('category')->render();
    return $content;
});

The documents (same for 5.0 & 5.1) say that to 'customize' the URI you can use the setPath() method.

This appears to work as far as I can see, but there are two issues I'm a bit confused about:

  1. The links are to the root of the site unless I use setPath() to change them. Reading the docs I expected to need to use setPath('events/category'), but in fact setPath('category') produces the correct links.

  2. Why do I need to code part of the URI into this at all? I didn't need to tell L4 to use 'whatever page you are on' as the URI. Is there some reason the current URI isn't the default?

If there is a better approach to this I'm all ears!
Thanks :)

0 likes
2 replies
nztim's avatar

Thanks Bobby, what I got from your post there is that I can pass the base URI and query into the paginator constructor to tidy it up, and it also removes the requirement for appends() in the view:

$paginated = new Illuminate\Pagination\LengthAwarePaginator($items, $events->count(), $perPage, $currentPage, ['path' => $request->url(), 'query' => $request->query()]);

Please or to participate in this conversation.