spatie/laravel-json-api-paginate
Adds a jsonPaginate() method to Laravel’s Eloquent/Query Builder that follows the JSON:API pagination spec. Reads page[number] and page[size] request params and generates the required pagination links for API responses.
Install the package via Composer: composer require spatie/laravel-json-api-paginate. Then, replace Laravel’s default paginate() calls with JsonApiPaginate::paginate() (or ->jsonApiPaginate() on queries). The package auto-converts pagination metadata to符合 JSON API spec (e.g., meta.pagination, links.self, links.first, etc.). First use case: Paginate any Eloquent query for a JSON API-compliant API response—e.g., User::jsonApiPaginate(20).
Use in controllers with standard query building:
$users = User::where('active', true)
->jsonApiPaginate(request('page.size', 25));
return $users;
For collection resources with includes or custom data: Apply ->jsonApiPaginate() after any with(), where(), etc., but before get() or first(). Combine with JsonApiResource::collection() if needed, but avoid wrapping paginated responses in custom transformers to prevent metadata loss. Leverage route-level parameter binding (e.g., @param int $page_size) for type-safe pagination control. Configure default page sizes and limits via config('json-api-paginate').
⚠️ Metadata only: The paginator returns only the paginated data and JSON API-compliant pagination metadata—no top-level data wrapper unless using resources. If returning raw Eloquent models, ensure your API resource layer doesn’t override the metadata.
⚠️ Page parameters: The package expects page[size] and page[number] by default (per JSON API spec). If your frontend sends limit/offset, manually map them in middleware or adjust config.
💡 Use JsonApiPaginate::currentPageResolver() to override pagination page detection (e.g., for custom pagination schemes).
💡 For testing, assert jsonApiPaginate responses with $this->assertJsonStructure(['data', 'links', 'meta.pagination']) to validate spec compliance.
💡 Remember to clear Laravel config cache (php artisan config:clear) after updating config/json-api-paginate.php, as config is cached.
How can I help you explore Laravel packages today?