问题
I have a complex query that is not based on any specific model table that I want to paginate output for. However laravel's built in pagination relies on models and tables. How can I paginate a collection and have the output match up with laravel's built in pagination output format?
回答1:
I keep this in an app\Core\Helpers class so that I can call them from anywhere as \App\Core\Helpers::makePaginatorForCollection($query_results). The most likely place to use this is the last line of a controller that deals with complex queries.
In app/Http/Controllers/simpleExampleController.php
/**
* simpleExampleController
**/
public function myWeirdData(Request $request){
$my_unsafe_sql = '...';//never do this!!
$result = DB::statement(DB::raw($my_unsafe_sql));
return \App\Core\Helpers::makePaginatorForCollection($result);
}
In app\Core\Helpers.php or anywhere you like that auto loads.
/**
* This will match laravel's built in Model::paginate()
* because it uses the same underlying code.
*
* @param \Illuminate\Support\Collection $collection
*
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
public static function makePaginatorForCollection(\Illuminate\Support\Collection $collection){
$current_page = (request()->has('page')? request()->page : 1) -1;//off by 1 (make zero start)
$per_page = (request()->has('per_page')? request()->per_page : config('api.pagination.per_page')) *1;//make numeric
$page_data = $collection->slice($current_page * $per_page, $per_page)->all();
return new \Illuminate\Pagination\LengthAwarePaginator(array_values($page_data), count($collection), $per_page);
}
/**
* Copy and refactor makePaginatorForCollection()
* if collection building is too slow.
*
* @param $array
*
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
public static function makePaginatorForArray($array){
$collection = collect($array);
return self::makePaginatorForCollection($collection);
}
来源:https://stackoverflow.com/questions/45022316/how-do-i-paginate-a-collection-or-custom-query-into-api-json-in-laravel