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


    <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>
    document.getElementById('pagination').onchange = function() { 
        window.location = "{{ $members->url(1) }}&items=" + this.value; 

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')

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

Leave a comment

Your email address will not be published. Required fields are marked *

4 thoughts on “Allow user to choose pagination length via dropdown (Laravel)

  • rakesh

    this is my students.blade.php


    public function getstudents(Request $request)

    $students =DB::table(‘users’)

    $students =DB::table(‘users’)
    $links = str_replace(‘/?’, ‘?’, $students->render());
    return view(‘students’,compact(‘students’));

    here users is a table
    where is mistake? it loads but after refreshing it loads default value

    • Mark Post author

      What is this supposed to be doing $links = str_replace(‘/?’, ‘?’, $students->render());

      You cannot post code in comments here, suggest you start a question on laracasts discussion forum