Laravel中針對集合進行分頁

在開發的過程中,遇到過一些需求;需要在分頁之前對數據進行一些調整(如:爲每條數據增加一個屬性「可根據此屬性進行查詢或篩選」),此時我想到的一個方案就是手動對查詢出來的集合進行分頁。

代碼示例:

public function index(Request $request){
	//獲取學生數據 並 爲每一個學生數據增加一個自定義屬性
	$students = Student::all()
	    ->each(function (Student $student){
	       return $student->customize_attr = 'test';
	    });
	// 對數據進行手動分頁
	$per_page = $request->get('per_page',10); // 每頁顯示的條數
	$result = $this->paginateCollection($users, $per_page);

	return ApiResponse::Success($result);
}

/**
 * 自定義分頁方法
 * @param $collection
 * @param $perPage
 * @param string $pageName
 * @param null $fragment
 * @return \Illuminate\Pagination\LengthAwarePaginator
 */
protected function paginateCollection($collection, $perPage, $pageName = 'page', $fragment = null)
{
    $currentPage = \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage($pageName);
    $currentPageItems = $collection->slice(($currentPage - 1) * $perPage, $perPage)->values();
    parse_str(request()->getQueryString(), $query);
    unset($query[$pageName]);
    $paginator = new \Illuminate\Pagination\LengthAwarePaginator(
        $currentPageItems,
        $collection->count(),
        $perPage,
        $currentPage,
        [
            'pageName' => $pageName,
            'path' => \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPath(),
            'query' => $query,
            'fragment' => $fragment
        ]
    );

    return $paginator;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章