Created
February 17, 2021 07:37
-
-
Save Elshaden/f886cd0595e1562a9c1e5c1f5b66f682 to your computer and use it in GitHub Desktop.
Convert Paginated API Response to standard Laravel Paginated collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This class is used to convert any API Response which has pagination into standrad Laravel Pagination collection | |
* to use it | |
* $PaginatedResponse = PaginateApiResponsne::paginate($YourAPIResponse); | |
* You will need to change the parameteres in the functin to match your Api response Pagination parameters | |
* | |
*/ | |
use Illuminate\Container\Container; | |
use Illuminate\Pagination\LengthAwarePaginator; | |
use Illuminate\Pagination\Paginator; | |
class PaginateApiResponsne | |
{ | |
/** | |
* | |
* @param $Response | |
* @return LengthAwarePaginator | |
*/ | |
public static function paginate($Response) | |
{ | |
$ApiMeta = $Response['meta']['pagination']; | |
$items = collect($Response['data']); | |
$pageSize = $ApiMeta['per_page']; | |
$page = $ApiMeta['current_page']?? 1 ; | |
$total = $ApiMeta['total'];; | |
return self::paginator($items, $total, $pageSize, $page, [ | |
'path' => Paginator::resolveCurrentPath(), | |
'pageName' => 'page', | |
]); | |
} | |
/** | |
* Create a new length-aware paginator instance. | |
* | |
* @param \Illuminate\Support\Collection $items | |
* @param int $total | |
* @param int $perPage | |
* @param int $currentPage | |
* @param array $options | |
* @return \Illuminate\Pagination\LengthAwarePaginator | |
*/ | |
protected static function paginator($items, $total, $perPage, $currentPage, $options) | |
{ | |
return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact( | |
'items', 'total', 'perPage', 'currentPage', 'options' | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment