{"id":35659442,"url":"https://github.com/brainstudnl/json-api-resource","last_synced_at":"2026-02-06T17:11:34.284Z","repository":{"id":62496604,"uuid":"475884681","full_name":"brainstudnl/json-api-resource","owner":"brainstudnl","description":"Make your Laravel API JSON:API compliant with the brainstud/json-api-resource package.","archived":false,"fork":false,"pushed_at":"2025-07-09T09:40:56.000Z","size":262,"stargazers_count":0,"open_issues_count":2,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-19T02:24:53.566Z","etag":null,"topics":[],"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/brainstudnl.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-03-30T13:11:22.000Z","updated_at":"2025-07-09T09:40:59.000Z","dependencies_parsed_at":"2024-06-04T07:55:14.576Z","dependency_job_id":"9969aeee-7861-4637-bd93-1a9af6263f55","html_url":"https://github.com/brainstudnl/json-api-resource","commit_stats":{"total_commits":30,"total_committers":4,"mean_commits":7.5,"dds":"0.33333333333333337","last_synced_commit":"f4577f7aa928478dcc09a4a3762d5cd76d731220"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"purl":"pkg:github/brainstudnl/json-api-resource","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brainstudnl%2Fjson-api-resource","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brainstudnl%2Fjson-api-resource/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brainstudnl%2Fjson-api-resource/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brainstudnl%2Fjson-api-resource/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/brainstudnl","download_url":"https://codeload.github.com/brainstudnl/json-api-resource/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/brainstudnl%2Fjson-api-resource/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28217412,"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","status":"online","status_checked_at":"2026-01-05T02:00:06.358Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":[],"created_at":"2026-01-05T16:17:11.501Z","updated_at":"2026-02-06T17:11:34.274Z","avatar_url":"https://github.com/brainstudnl.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JSON:API Resource for Laravel\n\nMake your Laravel API [JSON:API](https://jsonapi.org/) compliant with the `Brainstud\\JsonApi` package.\n\n## Table of contents\n\n- [Installation](#installation)\n- [Usage](#usage)\n- [Relationships](#relationships)\n- [Resource depth](#resource-depth)\n- [Exception handler](#exception-handler)\n- [Example](#example-usage)\n- [Deprecated `register` method](#defining-resources-via-the-register-method)\n- [Tweaking responses](#tweak-response)\n- [License](#license)\n\n## Installation\n\nRequire the package\n\n```bash\ncomposer require brainstud/json-api-resource\n```\n\n## Usage\n\n- Let your resource object extend from `JsonApiResource` instead of `JsonResource`.\n- Set the type of your resource as a string in `$this-\u003etype`.\n- For each part of your resource, define the matching `to{resourcePart}` method.\n\n```php\nclass Resource extends JsonApiResource\n{\n    protected string $type = 'resources';\n\n    protected function toAttributes(Request $request): array\n    {\n        return [\n            'field' =\u003e $this-\u003eresource-\u003efield,\n            'other_field' =\u003e $this-\u003eresource-\u003eother_field,\n        ];\n    }\n\n    protected function toRelationships(Request $request): array\n    {\n        return [\n            'relation' =\u003e ['relationMethod', Relation::class],\n        ];\n    }\n\n    protected function toLinks(Request $request): array\n    {\n        return [\n            'type_of_link' =\u003e ['href' =\u003e 'link'],\n        ];\n    }\n\n    protected function toMeta(Request $request): array\n    {\n        return [\n            'meta' =\u003e 'data',\n        ];\n    }\n}\n```\n\n## Relationships\n\n[JSON:API: Includes](https://jsonapi.org/format/#fetching-includes)\nFor the relationships to be included they need to be loaded. This can be done by implementing a `?include` parameter or using [spatie/laravel-query-builder](https://spatie.be/docs/laravel-query-builder/v3/introduction).\n\n## Resource depth\n\nThe resource depth has a default of 2. This can be changed by passing an array to the resource where the second item is the required resource depth.\nIn the following example we use a depth of 3:\n\n```php\npublic function show(ShowCourseRequest $request, Course $course)\n{\n    $query = (new CoursesQueryBuilder)-\u003efind($course-\u003eid);\n    return new CourseResource([$query, 3]);\n}\n```\n\nWhich allows us to ask for an include nested 3 levels deep: `/courses/{identifier}?include=content,content.answers,content.answers.feedback`\n\n## Exception handler\n\nThis package contains an exception handler to render exceptions as JSON:API error messages.\nEither use this handler directly by editing your `app.php` and registering this singleton\n\n```php\n// app.php\n$app-\u003esingleton(\n    Illuminate\\Contracts\\Debug\\ExceptionHandler::class,\n    \\Brainstud\\JsonApi\\Handlers\\JsonApiExceptionHandler::class\n);\n```\n\nOr register your own exception handler and delegate the render to the `JsonApiExceptionHandler::render` method.\n\n```php\n// app.php\n$app-\u003esingleton(\n    Illuminate\\Contracts\\Debug\\ExceptionHandler::class,\n    App\\Exceptions\\Handler::class\n);\n\n// handler.php\npublic function render($request, Throwable $exception)\n{\n    if ($request-\u003ewantsJson()) {\n        return (new JsonApiExceptionHandler($this-\u003econtainer))-\u003erender($request, $exception);\n    }\n\n    return parent::render($request, $exception);\n}\n```\n\n### Return error response\n\nThere are multiple ways to return an error page\n\n```php\n// Throw an exception that will be handled by the JsonApiExceptionHandler\nthrow new UnprocessableEntityHttpException();\n\n// Return a defined error response\nreturn (new UnprocessableEntityError)-\u003eresponse();\n\n// Return a custom error response\nreturn ErrorResponse::make(new DefaultError(\n    'PROCESSING_ERROR',\n    'Could not save item',\n    'An error occurred during saving of the item'\n), Response::HTTP_INTERNAL_SERVER_ERROR);\n```\n\n## Example usage\n\n```php\n// Course.php\n\n/**\n * @property int $id\n * @property string $title\n * @property string $description\n * @property Carbon $created_at\n * @property Collection $enrollments\n */\nclass Course extends Model\n{\n    protected $fillable = [\n        'title',\n        'description',\n    ];\n\n    public function enrollments(): HasMany\n    {\n        return $this-\u003ehasMany(Enrollment::class);\n    }\n}\n\n// CourseResource.php\n\n/**\n * @property Course $resource\n */\nclass CourseResource extends JsonApiResource\n{\n    protected string $type = 'courses';\n\n    protected function toAttributes(Request $request): array\n    {\n        return [\n            'title' =\u003e $this-\u003eresource-\u003etitle,\n            'description' =\u003e $this-\u003eresource-\u003edescription,\n            'created_at' =\u003e $this-\u003eresource-\u003ecreated_at-\u003eformat('c'),\n        ];\n    }\n\n    protected function toRelationships(Request $request): array\n    {\n        return [\n            'enrollments' =\u003e ['enrollments', EnrollmentResourceCollection::class],\n        ];\n    }\n\n    protected function toLinks(Request $request): array\n    {\n        return [\n            'view' =\u003e ['href' =\u003e $this-\u003eresource-\u003egetShowUrl()],\n        ];\n    }\n\n    protected function toMeta(Request $request): array\n    {\n        return [\n            'enrollments' =\u003e $this-\u003eresource-\u003eenrollments-\u003ecount(),\n        ];\n    }\n}\n\n\n// CoursesController.php\n\nclass CoursesController\n{\n    public function index(IndexCoursesRequest $request)\n    {\n        $query = (new CoursesQueryBuilder)-\u003ejsonPaginate();\n        return new CourseResourceCollection($query);\n    }\n\n    public function show(ShowCourseRequest $request, Course $course)\n    {\n        $query = (new CoursesQueryBuilder)-\u003efind($course-\u003eid);\n        return new CourseResource($query);\n    }\n}\n```\n\n## Defining resources via the `register` method\n\nIn the previous version of the package, you would have to define the resource structure via a register method.\nThis is still possible, but it is **deprecated** and will be removed in a later version.\n\nTo use this way of defining a resource, simply define a `register` method in your resource:\n\n```php\nprotected function register(): array\n{\n    return [\n        'id' =\u003e $this-\u003eresource-\u003eidentifier,\n        'type' =\u003e 'object_type',\n        'attributes' =\u003e [\n            'field' =\u003e $this-\u003eresource-\u003efield,\n            'other_field' =\u003e $this-\u003eresource-\u003eother_field,\n        ],\n        'relationships' =\u003e [\n            'items' =\u003e ['items', ItemsResourceCollection::class],\n            'item' =\u003e ['item', ItemResource::class],\n        ],\n        'meta' =\u003e [\n            'some_data' =\u003e 'some value',\n        ],\n        'links' =\u003e [\n            'some_key' =\u003e 'some link',\n        ],\n    ];\n}\n```\n\n## Tweak response\n\nThe `register` method doesn't have access to `$request` like `toArray` of `JsonResource` has.\nIf you want to manipulate the response based on the request this can be done by overriding the `addToResponse` method.\n\n```php\nprotected function addToResponse($request, $response): array\n{\n    if ($this-\u003erequestWantsMeta($request, 'data')\n        \u0026\u0026 ($data = $this-\u003egetData())\n    ) {\n        $response['meta']['data'] = $data;\n    }\n\n    return $response;\n}\n```\n\n## License\n\nJsonApi is open-sourced software licensed under the [MIT Licence](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrainstudnl%2Fjson-api-resource","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbrainstudnl%2Fjson-api-resource","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbrainstudnl%2Fjson-api-resource/lists"}