该技能面向 Laravel 的 API Resource 开发,整理资源转换、集合处理、条件属性与关系加载的最佳实践。
用途:为 Laravel 应用编写规范的 JsonResource 与 ResourceCollection,统一 API 输出结构,避免 N+1 查询。
主要能力:
- 基础资源结构:继承 JsonResource,在 toArray 中返回字段,日期用 toISOString() 格式化。
- 条件属性:whenLoaded 仅在关系已加载时输出;when 按条件输出;mergeWhen 条件合并字段。
- 嵌套关系:单关系用 new UserResource($this->whenLoaded('user')),集合关系用 CommentResource::collection(...)。
- 资源集合:继承 ResourceCollection,输出 data、meta(total、count、per_page、current_page、total_pages)与 links(self、first、last、prev、next)。
- 链接与响应定制:在 toArray 中加入 route 链接;控制器中可用 response()->setStatusCode(201)->header(...)。
- 中间表数据:whenPivotLoaded 与 whenPivotLoadedAs 输出 pivot 字段。
- 包装控制:JsonResource::withoutWrapping() 或静态 $wrap;with() 添加附加数据,withResponse() 设置响应头。
使用方式:在控制器中返回 new PostCollection(Post::with([...])->withCount('comments')->paginate(15)) 或 new PostResource($post);关系用 whenLoaded 加载。
适用场景:Laravel REST API 的响应层设计,尤其是需要分页元数据、HATEOAS 链接与按权限裁剪字段的项目。
限制:资料未提供安装命令、版本要求、性能基准或收费信息;示例基于 Laravel 的 JsonResource 与 ResourceCollection,需项目已具备相应框架环境。