[英]How to limit amount of pages in laravel pagination?
我有一個分頁並嘗試限制該分頁的頁數。 每頁有 50 個結果,我希望這個分頁的最大頁數是 200(表中的總條目數為 10k)。 我嘗試了以下方法:
$page_count = 50;
$users = DB::Table('user_totalpoints')->where('points', '>', 0)
->orderBy('points', 'desc')
->orderBy('id', 'asc')
->take(10000)
->paginate($page_count);
這樣做的結果是一個分頁,每頁有 50 個結果,但所有條目都來自 user_totalpoints 表。 take(10000) 被忽略,因為分頁只有 50 個。 因此,我現在有數千頁,而不是最多 200 頁。
如何限制 laravel 中分頁的頁數?
$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 ]);
// 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.