Ad

How To Limit Amount Of Pages In Laravel Pagination?

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?

Ad

Answer

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
Ad
source: stackoverflow.com
Ad