当信息不读取数据库时,如何将信息列表转换为分页Laravel
$list=[1,2,3,4,5,6,7,9];
/* how this line work*/
$list=$list->paginate(3);
您可以使用forPage
收集助手
$list = collect([1,2,3,4,5,6,7,9]);
$list->forPage(1, 3)->values() // collect([1,2,3])
$list->forPage(2, 3)->values() // collect([4,5,6])
$list->forPage(3, 3)->values() // collect([7,8,9])
$list->forPage(4, 3)->values() // collect([10])
$list->forPage(5, 3)->values() // collect()
如果您想要完整的分页器(带有links()
(,则需要更多的逻辑。
use IlluminatePaginationLengthAwarePaginator;
use IlluminatePaginationPaginator;
$list = collect([1,2,3,4,5,6,7,8,9]);
$pageName = 'page';
$perPage = 3;
$page = Paginator::resolveCurrentPage($pageName);
$total = $list->count();
$results = $total ? $this->forPage($page, $perPage)->values() : collect();
$options = ['path' => Paginator::resolveCurrentPath(), 'pageName' => $pageName];
$paginated_list = new LengthAwarePaginator($results, $total, $perPage, $page, $options);
此代码基于查询生成器上的paginate()
方法。
public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null) { $page = $page ?: Paginator::resolveCurrentPage($pageName); $total = $this->getCountForPagination(); $results = $total ? $this->forPage($page, $perPage)->get($columns) : collect(); return $this->paginator($results, $total, $perPage, $page, [ 'path' => Paginator::resolveCurrentPath(), 'pageName' => $pageName, ]); }