Search code examples
laravellaravel-7laravel-pagination

Laravel - what does the manual paginations 'option' query parameter do?


The manual pagination I found while googling works fine but I was just wondering what does the 'query' => $request->query() in the option parameter does?

$total = count($form_list);
$per_page = 10;
$current_page = $request->input('page') ?? 1;
$starting_point = ($current_page * $per_page) - $per_page;

$form_list = array_slice($form_list, $starting_point, $per_page, true);

$form_list = new Paginator($form_list, $total, $per_page, $current_page, [
    'path' => $request->url(),
    'query' => $request->query(),
]);

Solution

  • Calling ->query() without any parameters returns all the values from the query string as an associative array.

    Suppose you have a query string like this:

    https://example.com/path/to/page?name=ferret&color=purple
    

    You can retrieve the value of name by doing something like so:

    $request->query('name')
    

    which returns ferret. You can also pass a second parameter for a default value so if you call:

    $request->query('size', 'Medium')
    

    which doesn't exist on the query string, you'll get 'Medium' instead of null.

    If you omit all parameters, you'll receive an associative array that looks something like this:

    query = [
      'name' => 'ferret',
      'color' => 'purple',
    ]
    

    The options parameter is not needed by the pagination itself but for your dataset query. If you do not pass the query parameter, when you click one of the pagination urls, you'll get something like this:

    https://example.com/path/to/page?page=2&per_page=5
    

    Sometimes, this works fine and will give us something that we want but sometimes, we need those additional query string to get the correct dataset. We pass in all values from our query to get something like this:

    https://example.com/path/to/page?page=2&per_page=5&name=ferret&color=purple
    

    Which will filter your dataset for all those purple ferrets. As for the question if you need it, it's up for you to decide if that is essential for your code or if you can get away with just pagination.

    Good luck! I hope this helps.