Shokouh Dareshiri
Shokouh Dareshiri

Reputation: 946

How can I Paginate data which are in array?

I am using Laravel 5.7. I construcet an array like below:

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

$clientGames = array();

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

How can I paginate this array in Laravel?

Upvotes: 0

Views: 76

Answers (1)

Shokouh Dareshiri
Shokouh Dareshiri

Reputation: 946

I used below way to solve my question:

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

Upvotes: 1

Related Questions