如何对数组中的数据进行分页?

时间:2019-10-22 11:41:29

标签: arrays laravel collections pagination

我正在使用Laravel 5.7。我构造如下数组:

$games = GameResource::collection(Game::all());

$clientGames = array();

foreach ($games as $game) {
   if (!$game->user->inRole('admin')) {
        array_push($clientGames, $game);
   }
}

如何在Laravel中分页此数组?

1 个答案:

答案 0 :(得分:2)

我通过以下方式解决了我的问题:

$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;