Last active
December 28, 2022 04:36
-
-
Save vijaybajrot/1540a0bc1959a04f811e24cb04e72063 to your computer and use it in GitHub Desktop.
Get paginate links and data for Json Response with `data` and `links` keys.
This file contains hidden or 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
<?php | |
namespace App\Macros\QueryBuilder; | |
use Illuminate\Support\Collection; | |
use Illuminate\Database\Eloquent\Builder; | |
class JsonPaginate | |
{ | |
/** | |
* Load Macro in AppServiceProvider.php in boot method. | |
* Example : (new JsonPaginate())->loadMacro(); | |
* Call like this : User::with('posts)->jsonPaginate() or User::with('posts)->jsonSimplePaginate(); | |
* @author [email protected] <Vijay Bajrot> | |
* @return Illuminate\Support\Collection | |
*/ | |
public function loadMacro() | |
{ | |
$this->macro(); | |
} | |
public function macro() | |
{ | |
$self = new static; | |
Builder::macro('jsonPaginate', function () use ($self){ | |
return $self->mapPaginatorToLinks($this->paginate()); | |
}); | |
Builder::macro('jsonSimplePaginate', function () use ($self){ | |
return $self->mapPaginatorToLinks($this->simplePaginate()); | |
}); | |
} | |
public function mapPaginatorToLinks($paginator) | |
{ | |
return new Collection([ | |
'data' => $paginator->items(), | |
'links' => $this->getLinks($paginator), | |
]); | |
} | |
public function getLinks($paginator) | |
{ | |
return (new Collection($paginator->toArray()))->only($this->linksKeys()); | |
} | |
public function linksKeys() : Array | |
{ | |
return [ | |
"current_page", | |
"first_page_url", | |
"from", | |
"last_page", | |
"last_page_url", | |
"next_page_url", | |
"path", | |
"per_page", | |
"prev_page_url", | |
"to", | |
"total", | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment