Home > Enterprise >  How to limit amount of pages in laravel pagination?
How to limit amount of pages in laravel pagination?

Time:01-08

I have a pagination and try to limit the amount of pages for that pagination. Every page has 50 results and the maximum amount of pages I want for this pagination is 200 (10k total entries from the table). I tried the following:

$page_count = 50;
$users = DB::Table('user_totalpoints')->where('points', '>', 0)
        ->orderBy('points', 'desc')
        ->orderBy('id', 'asc')
        ->take(10000)
        ->paginate($page_count);

The result of this is a pagination with 50 results per page but with ALL entries from the user_totalpoints table. take(10000) is ignored as there are only 50 taken by the pagination. So instead of maximum 200pages I now have thousands.

How can I limit the amount of pages for my pagination in laravel?

CodePudding user response:

Manual Paginator LengthAwarePaginator

// limit page max to 200 and min to 1
$this->validate($request, [
    'page' => 'required|integer|min:1|max:200'
]);
$page = $request->get('page');
$page_count = 50;
$total = 10000;

$users = DB::Table('user_totalpoints')->where('points', '>', 0)
    ->orderBy('points', 'desc')
    ->orderBy('id', 'asc')
    ->forPage($page, $page_count)
    ->get();
/**
 * use Illuminate\Pagination\LengthAwarePaginator;
 */
$paginator = new LengthAwarePaginator($users, $total, $page_count, $page);
dd($paginator->toArray()); // view result

CodePudding user response:

$collection = UserTotalPoint::where('points', '>', 0)
                      ->orderby('points', 'desc')
                      ->orderby('id', 'desc')
                      ->take(10000)
                      ->get();


$perPage = 50;

$currentPage = LengthAwarePaginator::resolveCurrentPage();

if ($currentPage == 1) {
    $start = 0;
}
else {
    $start = ($currentPage - 1) * $perPage;
}

$currentPageCollection = $collection->slice($start, $perPage)->all();

$paginatedTop = new LengthAwarePaginator($currentPageCollection, count($collection), $perPage);

$paginatedTop->setPath(LengthAwarePaginator::resolveCurrentPath());


return view('topPoints', ['top' => $paginatedTop ]);
  •  Tags:  
  • Related