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.
When displaying the links, we need to append the current page length
{{ $members->appends(compact('items'))->links() }}
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
Thanks for this code. I had to change the script a bit as I was getting ‘whoops’ on the original code so my solution was:
document.getElementById(‘pagination’).onchange = function() {
window.location = “{{URL::route(‘mylabs’)}}?items=” + this.value;
};
Super Helpful!!!
I just needed this on an index page, so I used: window.location = “/clients?items=” + this.value;