我已经检查了相当薄的docs,但仍然不确定如何做到这一点。
我有一个收藏品。我希望手动创建一个分页器。
我想我必须在我的控制器中做一些事情:
new \Illuminate\Pagination\LengthAwarePaginator()
但是,我需要什么样的参数?我需要切片收集吗?另外,我如何显示'链接'在我看来?
有人可以发一个简单的例子来说明如何创建一个分页器吗?
请注意,我不想分页,例如。用户:: PAGINATE(10);
答案 0 :(得分:2)
请查看Illuminate\Eloquent\Builder::paginate
方法,了解如何创建一个。{/ p>
一个简单的例子,使用雄辩的模型来提取结果等:
$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
);
答案 1 :(得分:0)
你可以像这样创建一个Paginator:
$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);
}
要在视图中显示链接:
$paginatedCollection->links();
希望这有帮助!