Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add parameters to pagination

Tags:

laravel

lumen

into a Laravel Lumen API project, I give back a paginated result.

....
"next_page_url" is "http://example.com/something?pg=2"
....

How can I add to all links the parameters, which are included into the requested url?

Sample: http://example.com/something?pg=1&color=red&limit=2

next_page_url should then look like this: http://example.com/something?pg=2&color=red&limit=2

$queryStrings = Input::except('limit', 'order_by', 'order', 'page', 'count', 'current_page', 'last_page', 'next_page_url', 'per_page', 'previous_page_url', 'total', 'url', 'from', 'to', 'pg');
$limit = (Input::get('limit') ? Input::get('limit') : '10');
$order_by = (Input::get('order') ? Input::get('order') : 'id');
$order = (Input::get('order_by') ? Input::get('order_by') : 'asc');
$page = (Input::get('pg') ? Input::get('pg') : 1);

$query = DB::table('cars');

foreach ($queryStrings as $key => $value) {
    $query->where($key, '=', $value);
}

$query->select('id', 'car', 'color', 'active');
$query->orderBy($order_by, $order);

$paginated = $query->paginate($limit, ['*'], 'pg', $page);

return response()->json($paginated,200);

Thanks for help.

like image 235
Mondy Avatar asked Oct 26 '25 10:10

Mondy


1 Answers

You can use the appends() method available from the LengthAwarePaginator returned by the paginate() method. So you can simply add this line:

$paginated = $query->paginate($limit, ['*'], 'pg', $page);
$paginated->appends(Input::all());

return response()->json($paginated,200);

This will get all input values passed and append them to the links generated by the paginator. The appends() method mutates the instance on which it is called, that's why you simply need to call it on the result you get from paginate().

like image 175
Bogdan Avatar answered Oct 29 '25 01:10

Bogdan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!