ZoroCuba's avatar

How to use pagination with files list?

I am trying to paginate an array of files that I have on my local drive and searching the internet I found a way to generate the pagination manually.

public function render(BackupService $backupService, Request $request): View
{
    $files = $backupService->getAllBackups();
    $backups = $this->getPaginator($request, $files);
    return view('livewire.index-backup', compact('backups'));
}

public function getPaginator(Request $request, Array $items)
{
    $total = count($items);
    $page = $request->page ?? 1;
    $perPage = 3;
    $offset = ($page -1) * $perPage;
    $items = array_slice($items, $offset, $perPage);

    return new LengthAwarePaginator($items, $total, $perPage, $page, [
        'path' => route('security.backup.index'),
        'query' => $request->query()
    ]);
}

I have set the WithPagination trait required by Livewire. In the view, the files are paginated correctly but when I navigate through the pages it does not change the records, it only updates the url with the page that I select.

Only when I refresh the page is the correct records displayed and when executing any action within the component it is rendered again showing the records of page 1, but with the url of the page it was previously on.

If I remove the WithPagination trait, I can now navigate through the records through the links, but I still have the problem that when performing any action within the component, it renders showing the records of page 1.

Is there a way to make the manually generated pagination for an array of files allow dynamic navigation without the problems I mentioned?

0 likes
1 reply
Tray2's avatar

I would load all the files into an javascript array and then write the pagination in javascript.

Please or to participate in this conversation.