neclimdul / laravel-list-resource-collection
Hack to allow Laravel resource collections to list scalars.
Package info
gitlab.com/neclimdul/laravel-list-resource-collection
pkg:composer/neclimdul/laravel-list-resource-collection
Requires
- php: >=8.2
- illuminate/http: v12.*|v13.*
Requires (Dev)
- illuminate/pagination: v12.*|v13.*
- php-parallel-lint/php-parallel-lint: ^1.2
- phpspec/prophecy-phpunit: ^2.0
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ~2.1.2
- phpunit/phpunit: ^11.0
- squizlabs/php_codesniffer: ^4.0
README
Summary
When returning a paged results from Laravel, you're given a lot of tools using Resources to interact with Eloquents pager and provide rich, consistent JSON results. However, it assumes all your results are an array or objects. If you want to return a list of scalars, for example a list of IDs, it breaks.
This hacks package provides a Resource collection that hacks this process to allow a list of unprocesses scalars.
There's probably a better way, or maybe Laravel could better support this out of the box, but this solved the problem in the short term.
Example
<?php
$contacts = Contact::query()
->paginate(100, ['uuid']);
$contacts->setCollection($contacts->getCollection()->pluck('uuid'));
return new PaginatedResourceResponse(
ListResourceCollection::collection($contacts)
);