{"id":21992406,"url":"https://github.com/soyhuce/laravel-json-resources","last_synced_at":"2025-04-14T10:14:20.835Z","repository":{"id":41834826,"uuid":"467848366","full_name":"Soyhuce/laravel-json-resources","owner":"Soyhuce","description":"An opinionated JsonResource for Laravel","archived":false,"fork":false,"pushed_at":"2025-02-24T08:50:34.000Z","size":74,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-14T10:13:53.218Z","etag":null,"topics":["hacktoberfest","laravel"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Soyhuce.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"soyhuce"}},"created_at":"2022-03-09T08:55:17.000Z","updated_at":"2025-02-24T08:50:37.000Z","dependencies_parsed_at":"2024-04-29T16:41:53.413Z","dependency_job_id":"0ac4eb72-0faa-4b72-b891-6e341b872344","html_url":"https://github.com/Soyhuce/laravel-json-resources","commit_stats":{"total_commits":31,"total_committers":5,"mean_commits":6.2,"dds":0.5806451612903225,"last_synced_commit":"c9e8721ed851146855f70124606671523a3d3c22"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":"Soyhuce/package-skeleton-laravel","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Soyhuce%2Flaravel-json-resources","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Soyhuce%2Flaravel-json-resources/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Soyhuce%2Flaravel-json-resources/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Soyhuce%2Flaravel-json-resources/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Soyhuce","download_url":"https://codeload.github.com/Soyhuce/laravel-json-resources/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248860166,"owners_count":21173342,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest","laravel"],"created_at":"2024-11-29T20:13:42.577Z","updated_at":"2025-04-14T10:14:20.797Z","avatar_url":"https://github.com/Soyhuce.png","language":"PHP","funding_links":["https://github.com/sponsors/soyhuce"],"categories":[],"sub_categories":[],"readme":"# An opinionated JsonResource for Laravel\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/soyhuce/laravel-json-resources.svg?style=flat-square)](https://packagist.org/packages/soyhuce/laravel-json-resources)\n[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/soyhuce/laravel-json-resources/run-tests.yml?branch=main\u0026label=tests\u0026style=flat-square)](https://github.com/soyhuce/laravel-json-resources/actions?query=workflow%3Arun-tests+branch%3Amain)\n[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/soyhuce/laravel-json-resources/php-cs-fixer.yml?branch=main\u0026label=code%20style\u0026style=flat-square)](https://github.com/soyhuce/laravel-json-resources/actions?query=workflow%3A\"Fix+PHP+code+style+issues\"+branch%3Amain)\n[![GitHub PHPStan Action Status](https://img.shields.io/github/actions/workflow/status/soyhuce/laravel-json-resources/phpstan.yml?branch=main\u0026label=phpstan)](https://github.com/soyhuce/laravel-json-resources/actions?query=workflow%3APHPStan+branch%3Amain)\n[![Total Downloads](https://img.shields.io/packagist/dt/soyhuce/laravel-json-resources.svg?style=flat-square)](https://packagist.org/packages/soyhuce/laravel-json-resources)\n\nDon't ever run database queries in JsonResource serialization, without overhead in production !\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require soyhuce/laravel-json-resources\n```\n\nYou can publish the config file with:\n\n```bash\nphp artisan vendor:publish --tag=\"json-resources-config\"\n```\n\n## Usage\n\nThis package provides a base class `Soyhuce\\JsonResources\\JsonResource`.\n\nIt gives a simplified interface for data serialization :\n\n```php\nclass UserResource extends \\Soyhuce\\JsonResources\\JsonResource\n{\n    /**\n     * @return array\u003cstring, mixed\u003e\n     */\n    public function format(): array\n    {\n        return [\n            'id' =\u003e $this-\u003eid,\n            'email' =\u003e $this-\u003eemail,\n        ];\n    }\n}\n```\n\nIt is still possible tu use `public function toArray($request): array` method.\n\nA base class `\\Soyhuce\\JsonResources\\ResourceCollection` est aussi disponible.\n\n### Forbid to execute database queries\n\nUsing this base resource, you can forbid to execute database queries during serialization.\n\nYou just need to activate this option in `json-resources.forbid-database-queries` config.\n\nThis configuration is thought to be used in local environments but should be deactivated in production. It allows you to\ntests that all required relations are correctly loaded (in feature tests for exemple) while limiting overhead in\nproduction.\n\nFor exemple :\n\n```php\nclass UserResource extends \\Soyhuce\\JsonResources\\JsonResource\n{\n    /**\n     * @return array\u003cstring, mixed\u003e\n     */\n    public function format(): array\n    {\n        return [\n            'id' =\u003e $this-\u003eid,\n            'role' =\u003e $this-\u003erole-\u003elabel,\n        ];\n    }\n}\n\nclass UserController\n{\n    public function index(): \\Illuminate\\Http\\Resources\\Json\\JsonResource\n    {\n        return UserResource::collection(User::all());\n    }\n}\n```\n\nA `DatabaseQueryDetected` exception will be raised with every executed request :\n\n```txt\n2 queries detected in resource :\nselect * from \"roles\" where \"id\" = 2\nselect * from \"roles\" where \"id\" = 1\n```\n\n### AnonymousResource\n\nIt could be useful to have anonymous resources for some cases.\n\nFor exemple if user's role is nullable, you could have :\n\n```php\nclass UserResource extends \\Soyhuce\\JsonResources\\JsonResource\n{\n    /**\n     * @return array\u003cstring, mixed\u003e\n     */\n    public function format(): array\n    {\n        return [\n            'id' =\u003e $this-\u003eid,\n            'role' =\u003e $this-\u003erole !== null \n                ? [\n                    'id' =\u003e $this-\u003erole-\u003eid,\n                    'label' =\u003e $this-\u003erole-\u003elabel,\n                ]\n                : null\n        ];\n    }\n}\n```\n\nVia an `AnonymousResource`, you could do\n\n```php\nclass UserResource extends \\Soyhuce\\JsonResources\\JsonResource\n{\n    /**\n     * @return array\u003cstring, mixed\u003e\n     */\n    public function format(): array\n    {\n        return [\n            'id' =\u003e $this-\u003eid,\n            'role' =\u003e new \\Soyhuce\\JsonResources\\AnonymousResource(\n                $this-\u003erole,\n                fn (Role $role) =\u003e [\n                    'id' =\u003e $this-\u003erole-\u003eid,\n                    'label' =\u003e $this-\u003erole-\u003elabel,\n                ]\n            )\n        ];\n    }\n}\n```\n\nIf the user has a role, you will get :\n\n```json\n{\n  \"data\": {\n    \"id\": 1,\n    \"role\": {\n      \"id\": 2,\n      \"label\": \"classic\"\n    }\n  }\n}\n```\n\nIf the user doest not have a role, you will get :\n\n```json\n{\n  \"data\": {\n    \"id\": 1,\n    \"role\": null\n  }\n}\n```\n\n### Returning anonymous resource from the controller\n\nIt is possible to return an anonymous resource from the controller. In cas the provided data is null, you won't get '\nnull' but an empty array `[]`.\n\n```php\nclass SomeController\n{\n    public function show()\n    {\n        return \\Soyhuce\\JsonResources\\AnonymousResource::make(\n           $this-\u003esearchSomeItem(), // returns Item|null\n           fn (Item $item) =\u003e [\n               'label' =\u003e $item-\u003elabel,\n               'prop' =\u003e $item-\u003eprop \n           ]\n        );\n    }\n}\n```\n\nIf the item is found\n\n```json\n{\n  \"data\": {\n    \"label\": \"the label\",\n    \"prop\": 14\n  }\n}\n```\n\nIf the item is `null`\n\n```json\n{\n  \"data\": []\n}\n```\n\n\u003e Note : Anonymous resource collections are not supported\n\n#### AnonymousResource without format\n\nIt is possible to return an anonymous resource without callback. In this case, the resource will be returned as is.\n\n```php\nclass SomeController\n{\n    public function show()\n    {\n        $foo = $this-\u003efetchFoo();\n        $bars = $this-\u003efetchBars();\n        \n        return \\Soyhuce\\JsonResources\\AnonymousResource::make([\n           'foo' =\u003e FooResource::make($foo),\n           'bars' =\u003e BarResource::collection($bars), \n       ]);\n    }\n}\n```\n\nLe json retourné aura alors la forme\n\n```json\n{\n  \"data\": {\n    \"foo\": {\n      // some foo data\n    },\n    \"bar\": [\n      {\n        // some bar data\n      },\n      {\n        // some bar data\n      }\n    ]\n  }\n}\n```\n\n### Json encoding\n\nAll returned jsons are encoded by default with `JSON_PRESERVE_ZERO_FRACTION` option.\n\n### Feature tests\n\nThe `JsonResource` and `ResourceCollection` classes will add a `X-Json-Resource` header to the response when the\napplication is in `local` or `testing` environment.\n\nThis header will contain the actual resource class used to generate the response and can be used in functional tests to\nverify which resource was used.\n\nIn order to test this, you cas use `TestResponse::assertJsonResource(TheResource::class)` method.\n\n```php\nuse Soyhuce\\JsonResources\\Tests\\Fixtures\\User;\n\nclass SomeController\n{\n    public function index(): JsonResouce\n    {\n        return UserResource::collection(User::all());\n    }\n    \n    public function show(User $user): JsonResource\n    {\n        return UserResource::make($user);\n    }\n\n}\n\nclass UserTest extends TestCase\n{\n    /** @test */\n    public function indexUsesUserResource(): void\n    {\n        $this-\u003egetJson('users')\n            -\u003eassertOk()\n            -\u003eassertJsonResource(UserResource::class);\n    }\n    \n    /** @test */\n    public function showUsesUserResource(): void\n    {\n        $user = User:::factory()-\u003ecreateOne();\n        \n        $this-\u003egetJson(\"users/{$user-\u003eid}\")\n            -\u003eassertOk()\n            -\u003eassertJsonResource(UserResource::class);\n    }\n}\n```\n\n### Unit tests\n\nIt can be useful to unit test the `JsonResource`. You can\nuse [soyhuce/laravel-testing](https://github.com/Soyhuce/laravel-testing) for this.\n\nIn this cas, you will probably need to allow database queries to be run. You can do this calling\n\n```php\n\\Soyhuce\\JsonResources\\JsonResources::allowDatabaseQueries();\n```\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.\n\n## Security Vulnerabilities\n\nPlease review [our security policy](../../security/policy) on how to report security vulnerabilities.\n\n## Credits\n\n- [Bastien Philippe](https://github.com/bastien-phi)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsoyhuce%2Flaravel-json-resources","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsoyhuce%2Flaravel-json-resources","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsoyhuce%2Flaravel-json-resources/lists"}