How do I paginate a collection or custom query into API json in Laravel?

梦想与她 提交于 2019-12-11 15:17:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!