【问题标题】:How can I Paginate data which are in array?如何对数组中的数据进行分页?
【发布时间】:2020-02-18 13:23:06
【问题描述】:
我正在使用 Laravel 5.7。我构造了一个如下所示的数组:
$games = GameResource::collection(Game::all());
$clientGames = array();
foreach ($games as $game) {
if (!$game->user->inRole('admin')) {
array_push($clientGames, $game);
}
}
如何在 Laravel 中对这个数组进行分页?
【问题讨论】:
标签:
arrays
laravel
collections
pagination
【解决方案1】:
我用下面的方法来解决我的问题:
$per_page = !empty($_GET['per_page']) ? $_GET['per_page'] : 10;
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$clientGamesCollection = collect($clientGames);
$currentPageItems = $clientGamesCollection->slice(($currentPage * $per_page) - $per_page, $per_page)->all();
$paginatedItems= new LengthAwarePaginator($currentPageItems , count($clientGamesCollection), $per_page);
$paginatedItems->setPath($request->url());
$pagination = $paginatedItems;