shahabes's avatar

Multiple Array pagination

Hello, I have four arrays in my controller that should be paginated in the view. So, I'm using the following method to paginate arrays.

    public function paginate($items, $perPage = 5, $page = null, $options = [])
    {

        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);

        $items = $items instanceof Collection ? $items : Collection::make($items);

        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }

With only one array (one pagination per page) it works like a charm. But when some other arrays (pagination) come to the page, some problems occurred. To prevent conflict with the default page parameter of the pagination, i set the page name of the pagination by the following:

$times = $this->paginate($times, 5)->setPageName("timesPage")

When I click on the other pages of timePage, the url parameter changed but the page will not change. The pagination work only with the default page page name. Please help me solve the problem.

0 likes
1 reply
LaryAI's avatar
Level 58

One solution to this problem is to pass the page parameter explicitly to the paginate function for each array. Here's an example:

public function index()
{
    $array1 = [...];
    $array2 = [...];
    $array3 = [...];
    $array4 = [...];

    $perPage = 5;
    $page1 = request()->query('page1', 1);
    $page2 = request()->query('page2', 1);
    $page3 = request()->query('page3', 1);
    $page4 = request()->query('page4', 1);

    $paginator1 = $this->paginate($array1, $perPage, $page1)->withQueryString()->setPageName('page1');
    $paginator2 = $this->paginate($array2, $perPage, $page2)->withQueryString()->setPageName('page2');
    $paginator3 = $this->paginate($array3, $perPage, $page3)->withQueryString()->setPageName('page3');
    $paginator4 = $this->paginate($array4, $perPage, $page4)->withQueryString()->setPageName('page4');

    return view('index', compact('paginator1', 'paginator2', 'paginator3', 'paginator4'));
}

public function paginate($items, $perPage = 5, $page = null, $options = [])
{
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);

    $items = $items instanceof Collection ? $items : Collection::make($items);

    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}

In this example, we pass the page parameter explicitly to the paginate function for each array using the request()->query() method. We also set the page name for each paginator using the setPageName() method. Finally, we pass the paginators to the view and use them in the blade template as usual.

Note that we also use the withQueryString() method to preserve the query string parameters when generating the pagination links.

Please or to participate in this conversation.