Skip to content

Instantly share code, notes, and snippets.

@karakhanyans
Created February 12, 2021 12:44
Show Gist options
  • Save karakhanyans/337c054b3a2346bd56266fe72c6c7e4c to your computer and use it in GitHub Desktop.
Save karakhanyans/337c054b3a2346bd56266fe72c6c7e4c to your computer and use it in GitHub Desktop.
<?php
namespace App\Providers;
use App\Services\PaginationService;
use Illuminate\Support\Collection;
use Illuminate\Support\ServiceProvider;
class CollectionMacroServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: PaginationService::resolveCurrentPage($pageName);
return new PaginationService(
$this->forPage($page, $perPage)->values(),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => PaginationService::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
}
}
<?php
namespace App\Services;
use Illuminate\Pagination\LengthAwarePaginator;
class PaginationService extends LengthAwarePaginator
{
public function __construct(mixed $items, int $total, int $perPage, $currentPage = null, array $options = [])
{
parent::__construct($items, $total, $perPage, $currentPage, $options);
}
public function toArray(): array
{
return [
'data' => $this->items->toArray(),
'links' => [
'first' => $this->url(1),
'last' => $this->url($this->lastPage()),
'prev' => $this->previousPageUrl(),
'next' => $this->nextPageUrl()
],
'meta' => [
'current_page' => $this->currentPage(),
'from' => $this->firstItem(),
'last_page' => $this->lastPage(),
'links' => $this->linkCollection()->toArray(),
'path' => $this->path(),
'per_page' => $this->perPage(),
'to' => $this->lastItem(),
'total' => $this->total(),
]
];
}
}
@gcj5219
Copy link

gcj5219 commented May 31, 2021

postman_error
hi,

Can you tell me how to use this? I tried this so far

$data = Inquiry::latest()->get(); $data->paginateme(20);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment