Daily Archives: 28th January 2018


Allow user to choose pagination length via dropdown (Laravel)

The following technique allows the user of your site to choose the pagination length from a dropdown menu.

In this example, the members of a club are paginated.

The Select list is created as follows

 

<form>
    <select id="pagination">
        <option value="5" @if($items == 5) selected @endif >5</option>
        <option value="10" @if($items == 10) selected @endif >10</option>
        <option value="25" @if($items == 25) selected @endif >25</option>
    </select>
</form>
<script>
    document.getElementById('pagination').onchange = function() { 
        window.location = "{{ $members->url(1) }}&items=" + this.value; 
    }; 
</script>

Changing the dropdown causes the page to be reloaded, passing `items=10` etc to the controller. The controller checks for items or uses a default value.

    public function index(Request $request)
    {
        $items = $request->items ?? 10;      // get the pagination number or a default

        $club = Club::findOrFail(session('club'));

        $members = $club->members()->paginate($items);
       
        return view('club.' . config('app.locale') . '.index')
            ->withClub($club)
            ->withMembers($members)
            ->withItems($items);
    }

In the controller method, items is passed back to the view so that it can be used to ensure the current length is selected