Laravel 4 - How to use 'offset' in stead of 'page' with Eloquent's ->paginate()?

别等时光非礼了梦想. 提交于 2019-12-06 01:59:27

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!