Laravel 4 - How to use 'offset' in stead of 'page' with Eloquent's ->paginate()?
laravel, laravel-4, pagination, php
Solution
But then I cannot use the same controller for the API and the web view. So I would prefer some way to make the first one working.
Why not? If you already know `?offset` will be available in the API, and `?page` in your normal view. Just detect which is found and apply it appropriately.
That said, you can retrieve the paginator environment instance the query builder uses and pass it a page number that you define.
$perPage = 50;
$currentPage = 1;
if ($offset = Input::get('offset'))
{
$currentPage = ($offset / $perPage);
}
Warehouse::resolveConnection()->getPaginator()->setCurrentPage($currentPage);
$warehouses = Warehouse::orderBy('name')->paginate($perpage);
Note that, while I tested this and it works, I don't know how much it will affect other queries that you might run on the same page. Look into it, use with caution.
Problem
I am migrating an existing REST API to Laravel 4.1, and the API currently uses `offset` as querystring parameter to specify what the offset of the records needs to be. I would like to use the default Eloquent's `paginate()`, but these searches for the `page` querystring parameter. And of course it uses the page number (like 2) instead of the offset (like 200). Is there an easy way to configure the `paginate` function to this situation? Or do I need to use `->skip()` and `->take()` functions and make the links to the next page myself? @Anam: I want to use: ``` $warehouses = Warehouse::orderBy('name') ->paginate($perpage); ``` This works with http://example.org/api/warehouses?page=2, but I want this to work with http://example.org/api/warehouses?offset=200 With the offset I can use: ``` $warehouses = Warehouse::orderBy('name') ->skip($offset) ->take($perpage) ->get(); ``` But then I cannot use the same controller for the API and the web view. So I would prefer some way to make the first one working.