Laravel 5 和长度感知分页

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29527064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:19:35  来源:igfitidea点击:

Laravel 5 and Length Aware Pagination

laravellaravel-5

提问by Sturm

I've got another pagination problem it looks like. When I iterate over the paginated array below, I get the entire array every page.

我还有另一个分页问题。当我遍历下面的分页数组时,每页都会得到整个数组。

$array = [...];
$ret = new LengthAwarePaginator($array, count($array), 10);
// dd($ret);

LengthAwarePaginator {#302 ▼
  #total: 97
  #lastPage: 10
  #items: Collection {#201 ▼
    #items: array:97 [?]
  }
  #perPage: 10
  #currentPage: 1
  #path: "/"
  #query: []
  #fragment: null
  #pageName: "page"
}

This isn't the case when building a LAP from an eloquent model eg: Blah::paginate()

从 eloquent 模型构建 LAP 时情况并非如此,例如: Blah::paginate()

回答by Joseph Silber

The paginator does not slice the given array for you automatically. You have to slice it yourself before you pass it to the paginator.

分页器不会自动为您切片给定的数组。在将它传递给分页器之前,您必须自己切片。

To make life easier for you, use the collecthelper to create an instance of a laravel collection, which makes it very easy to slice up:

为了让你的生活更轻松,使用collect帮助器创建一个 Laravel 集合的实例,这使得切片变得非常容易:

$items = collect([...]);
$page = Input::get('page', 1);
$perPage = 10;

$paginator = new LengthAwarePaginator(
    $items->forPage($page, $perPage), $items->count(), $perPage, $page
);

回答by Sturm

The LengthAwarePaginator does not chunk autmoatically.

LengthAwarePaginator 不会自动分块。

An quick fix is to do something similar:

一个快速的解决方法是做类似的事情:

foreach($col->slice($col->perPage() * ($col->currentPage() - 1), $col->perPage()) as $item)
{
     // do blah
}