最近遇到一些需求。需要在分页输出前对数据进行一些调整,然后再输出分页,找到一个手动对 Collection 分页的方案,下面是示例代码:
// 获取所有用户
$users = User::all();
// 为每个用户添加一个属性
$users->each(function($user) {
$user->foo = 'bar';
});
// 对数据进行手动分页
$per_page = 5; // 每页显示5条
$users = $this->paginateCollection($users, $per_page);
return View('users', compact('users'));
下面是分页方法:
protected function paginateCollection($collection, $perPage, $pageName = 'page', $fragment = null)
{
$currentPage = \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
$currentPageItems = $collection->slice(($currentPage - 1) * $perPage, $perPage)->values();
parse_str(request()->getQueryString(), $query);
unset($query[$pageName]);
$paginator = new \Illuminate\Pagination\LengthAwarePaginator(
$currentPageItems,
$collection->count(),
$perPage,
$currentPage,
[
'pageName' => $pageName,
'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
'query' => $query,
'fragment' => $fragment
]
);
return $paginator;
}