PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

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

 March 01, 2022     arrays, collections, laravel-5, pagination, paginator     No comments   

Issue

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


Answered By - Tarek Adam
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing