Daily archives: 25th February 2017


Using multiple Laravel pagination links on one page

I came across a problem in a Laravel 5.3 project where I wanted two independent paginated areas on a single view.

multiple-pagination

Using just {{ $model->links() }} on the page would cause both lists to be paged at the same time since the URL contains ?page=1 and does not distinguish which set is being paged.

The answer is to include additional parameters to the paginate() function in the controller.

https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_paginate

By passing in a third parameter we can change the default ‘page’ to a name that can vary for our two sets of data.

 

    public function index()
    {
        $cbShows = Show::champBreed()->paginate(150, ['*'], 'cbShows');
        $owShows = Show::openWorking()->paginate(300, ['*'], 'owShows');

        return view('shows.index')->with(compact('owShows','cbShows'));
    }

We can now page through the two sets of data independently. The links will be adapted like

/shows?owShows=3

The second parameter [‘*’] is an array of the columns to be selected and must be set in order to allow the third parameter to be passed.