如何创建分页器?

How to create a paginator?

我已经检查了相当薄的 docs,但仍然不确定该怎么做。

我有一个collection。我想手动创建一个分页器。

我想我必须在我的控制器中做类似的事情:

new \Illuminate\Pagination\LengthAwarePaginator()

但是,我需要什么参数,我需要对 collection 进行切片吗?另外,我该如何在我的视图中显示 'links'?

有人可以 post 一个如何创建分页器的简单示例吗?

请注意,我不想分页 eloquent,例如。 User::paginate(10);

您可以像这样创建分页器:

$page = request()->get('page'); // By default LengthAwarePaginator does this automatically.
$collection = collect(...array...);
$total = $collection->count();
$perPage = 10;
$paginatedCollection = new \Illuminate\Pagination\LengthAwarePaginator(
                                    $collection,
                                    $total,
                                    $perPage,
                                    $page
                            );

根据LengthAwarePaginator(构造函数)的源代码

public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])
{
    foreach ($options as $key => $value) {
        $this->{$key} = $value;
    }
    $this->total = $total;
    $this->perPage = $perPage;
    $this->lastPage = (int) ceil($total / $perPage);
    $this->path = $this->path != '/' ? rtrim($this->path, '/') : $this->path;
    $this->currentPage = $this->setCurrentPage($currentPage, $this->pageName);
    $this->items = $items instanceof Collection ? $items : Collection::make($items);
}

See more about LengthAwarePaginator

要在视图中显示链接:

$paginatedCollection->links();

希望对您有所帮助!

查看 Illuminate\Eloquent\Builder::paginate 方法以获取有关如何创建的示例。

使用 eloquent 模型提取结果等的简单示例:

$page = 1; // You could get this from the request using request()->page
$perPage = 15;
$total = Product::count();
$items = Product::take($perPage)->offset(($page - 1) * $perPage)->get();

$paginator = new LengthAwarePaginator(
    $items, $total, $perPage, $page
);
  • 第一个参数接受要显示在您所在页面上的结果
  • 第二个是结果总数(您正在分页的项目总数,而不是您在该页面上显示的项目总数)
  • 第三个是你要显示的每页数
  • 第四个是您所在的页面。
  • 如果您还想自定义一些东西,您可以将额外的选项作为第五个参数传递。

您应该可以在分页器上使用 ->render()->links() 方法生成链接,就像您使用 Model::paginate()

一样

对于现有的项目集合,您可以这样做:

$page = 1;
$perPage = 15;
$total = $collection->count();
$items = $collection->slice(($page - 1) * $perPage, $perPage);

$paginator = new LengthAwarePaginator(
    $items, $total, $perPage, $page
);