Laravel分页不适用于数组而不是集合
我正在尝试对数组数据集进行分页,事实证明它比我想象的更具挑战性.
I'm trying to paginate an array data set and it has proven more challenging than I thought.
我正在使用Laravel 5
I'm using Laravel 5
所以我有一个抽象接口/存储库,所有其他模型都扩展到该接口/存储库,并在抽象存储库内部创建了一个名为paginate的方法. 我都包括了
So I have an abstract interface/repository that all my other models extend to and I created a method inside my abstract repository call paginate. I've included both
use Illuminate\Pagination\Paginator;
和
use Illuminate\Pagination\LengthAwarePaginator;
这是方法
public function paginate($items,$perPage,$pageStart=1)
{
// Start displaying items from this number;
$offSet = ($pageStart * $perPage) - $perPage;
// Get only the items you need using array_slice
$itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);
return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage,Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
}
因此,您可以想象此函数接受$items
数组,其中的$perPage
变量表示要分页的项目数,而$pageStart
则指示从哪个页面开始的数据.
So as you can imagine this function accepts an array of $items
a $perPage
variable that indicates how many to items to paginate and a $pageStart
that indicates from which page to start.
分页有效,当我执行dd()
时,我可以看到LengthAwarePaginator
实例,它的所有值似乎都很好.
The pagination works and I can see LengthAwarePaginator
instance when I'm doing a dd()
, all of it's values seem fine.
当我显示结果时问题就开始了.
The problem starts when I'm displaying the results.
当我执行{!! $instances->render() !!}
时,分页器链接显示正常,page
参数根据链接而变化,但数据未更改.
每页中的数据都相同.例如,当我使用Eloquent Model::paginate(3)
时,一切正常,但是当我dd()
此LengthAwarePaginator
时,它与我的自定义分页器的LengthAwarePaginator
实例相同,不同之处在于它对课程数组而不是集合进行分页
When I do {!! $instances->render() !!}
The paginator links display's fine, the page
parameter changes according to links but the data is not changing.
Data is the same in every page. When I'm using Eloquent for example Model::paginate(3)
everything works fine, but when I dd()
this LengthAwarePaginator
it's identical to the LengthAwarePaginator
instance of my custom paginator with the exception that it paginates an array ofcourse and not a collection.
您没有像当前那样传递当前页面,因此您也将获得相同的数组.这将起作用
You are not passing the current page, like you should so you also get same array. This will work
public function paginate($items,$perPage)
{
$pageStart = \Request::get('page', 1);
// Start displaying items from this number;
$offSet = ($pageStart * $perPage) - $perPage;
// Get only the items you need using array_slice
$itemsForCurrentPage = array_slice($items, $offSet, $perPage, true);
return new LengthAwarePaginator($itemsForCurrentPage, count($items), $perPage,Paginator::resolveCurrentPage(), array('path' => Paginator::resolveCurrentPath()));
}
如果您为$pageStart
-Request::get('page', 1)