Search code examples
arrayslaravel-5collectionspaginationpaginator

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


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?


Solution

  • 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);
    }