App-owned bounded collection pagination in Laravel PHP
Scope
Inline one collection paginate macro caller over a small, fully materialized authorized list using Laravel's own paginator. Preserve order, total, reindexed items and the endpoint's page/link/resource shape. Exclude other macros, unbounded/lazy sources, database pagination, supplied-total overrides and simple/cursor pagination. Retain excluded consumers. Preserve the upstream MIT notice for adapted code and check get-recipe's current port catalog for alternatives. This guidance has not been exercised in your app; verify it with the checks below.
Source behaviour
src/Macros/Paginate.php resolves a falsy page through the page resolver, uses forPage(...)->values(), defaults a falsy total to collection count and builds LengthAwarePaginator with path/page-name options. values() matters because sparse keys can otherwise serialize as JSON objects. Pagination itself does not authorize, filter or sort the source list.
src/CollectionMacroServiceProvider.php skips an already registered macro name; confirm that the real caller uses this implementation. tests/Macros/PaginateTest.php exercises count, page naming and URL behavior, not every other macro or invalid paging value.
Implementation
- Capture the caller's actual macro owner, authorized source bound, filters, ordering, sparse keys, page resolver, totals and response/link format. Keep large/database-backed sources on their native paginator. Loading all database records merely to remove a macro is not this recipe.
- Authorize/filter the complete bounded snapshot before computing count or items. Preserve deterministic order and any unique sort tie-breaker. Private or foreign rows must not leak through totals. Never mutate a shared cached collection to apply request filters/sorting.
- Parse page/size as integers before the adapter. The example deliberately rejects page zero and sizes outside 1..100 rather than reproducing upstream's falsy-page resolver. Use the endpoint's established limit if different. A huge positive page returns empty without overflowing the offset.
- Construct Laravel's
LengthAwarePaginatordirectly from reindexed page items and the same snapshot's count. Supply a trusted route path; preserve the caller's real page name and allowlisted query parameters using existing response/link code. Do not turn arbitrary request input into a path/host or unrestricted paginator options. The example deliberately omits caller-supplied total overrides. - Preserve resources and existing empty-list/metadata/error conventions. A pure snapshot read needs no new transaction/cache/migration; retain any existing consistency contract. Scoped cache identity includes tenant, permissions, filters, order, page and size, with existing invalidation. Remove the dependency only after every used macro has a replacement.
Complete adapter for a bounded, already authorized/ordered Collection, integer inputs and trusted path. It validates example limits, handles offset overflow before forPage, and preserves reindexing. Transport parsing, custom page names, query strings and resource projection remain the caller's responsibility:
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
function paginateItems(Collection $items, int $page, int $perPage, string $trustedPath): LengthAwarePaginator
{
if ($page < 1 || $perPage < 1 || $perPage > 100) {
throw new \InvalidArgumentException('invalid page or size');
}
$total = $items->count();
$pageItems = ($page - 1 > intdiv($total, $perPage)
? $items->take(0)
: $items->forPage($page, $perPage))->values();
return new LengthAwarePaginator($pageItems, $total, $perPage, $page, [
'path' => $trustedPath,
'pageName' => 'page',
]);
}
Adapt the method/name to the selected feature rather than installing a new global macro/helper merely to reproduce the syntax.
Acceptance checklist
- For ordered IDs
[31, 7, 42, 9, 18], size 2, assert pages[31, 7],[42, 9],[18], then[], total 5 and last page 3. Empty input yields[]and the declared Laravel metadata convention. - Reject page 0/negative/non-integer request input and sizes 0/101.
PHP_INT_MAXas a positive page returns empty without overflow or wrapping to page 1; out-of-range transport integers fail before coercion. - Start with sparse associative keys and assert the serialized
datais a JSON array. Compare source-backed links, custom page names/query parameters and resources. Retain unsupported supplied-total behavior until deliberately replaced. - Filter private/cross-tenant rows before totals; verify denied requests cannot access cached counts/items. Repeated sort values produce stable disjoint page IDs. Source collections remain unchanged across requests.
- Assert the materialization/memory bound. Search remaining macro calls and
composer why spatie/laravel-collection-macrosbefore removing the package.
Run the app's endpoint/resource/authorization/pagination tests, recording PHP/Laravel versions, decisive outputs and deliberate changes. The adapter's isolated tests do not establish the whole endpoint's compatibility.
Sources
- MIT reference source:
src/Macros/Paginate.php,src/CollectionMacroServiceProvider.php, andtests/Macros/PaginateTest.php. PreserveLICENSE.md. - Framework source checked:
src/Illuminate/Collections/Traits/EnumeratesValues.php,src/Illuminate/Collections/Collection.php, andsrc/Illuminate/Pagination/LengthAwarePaginator.php; reconcile metadata with the app's lockfile. - Port options: check
get-recipe's current port catalog (sourced from Package Port) at implementation time.