用途:在 Laravel 13 中构建符合 JSON:API 规范的 API 端点,基于第一方 JsonApiResource 基类,避免手写序列化器带来的规范偏差。
主要能力:JsonApiResource 继承 JsonResource 并处理规范细节;自动设置 Content-Type 为 application/vnd.api+json;支持稀疏字段集(?fields[posts]=title,created_at);支持关系包含(?include=author,comments 并生成 included 数组);在关系中输出资源标识符 {"id":"1","type":"posts"};可通过 toLinks() 与 toMeta() 覆盖链接和元数据。类型默认由类名推导(PostResource 对应 posts),仅在需要不同时覆盖 toType()。
用法要点:用 php artisan make:resource PostResource --json-api 生成资源;资源中使用 $attributes 与 $relationships 声明可暴露的字段和关系,使用 toAttributes() 而非 toArray();控制器返回 PostResource::collection(Post::with('author')->get())。客户端请求必须使用 Accept: application/vnd.api+json。建议对 include 使用预加载避免 N+1,并在 OpenAPI 中记录支持的 include 与 fields 参数。绕过资源(如自定义错误)时需自行设置响应 Content-Type。
限制:不要自行编写 JSON:API 序列化器或混用 toArray() 与 toAttributes();未列入白名单的关系会被静默忽略;不应返回缺少 JsonApiResource 基类的手工 JSON。资料还提到可选的智能体工作流与校验步骤,涉及 explore-codebase、research-expert、context7 文档查询及 sniper 验证,但具体运行环境与细节暂未提供。