关于 laravel:api-resources-and-pagination
用于 Laravel API 开发的技能,介绍如何借助 Resources 和分页组织响应。内容涵盖条件字段、保留分页元数据、响应契约版本管理,以及一方 JSON:API Resources。
主要功能
- 01使用 Resources 表示模型
- 02用 when() 和 mergeWhen() 设置条件字段
- 03保留分页链接与游标
- 04管理 API Resource 契约版本
- 05JSON:API Resource 模式
适用场景
- 01构建 Laravel 分页端点
- 02返回条件响应字段
- 03支持 JSON:API 客户端
- 04调整 API 响应契约
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ jpcaparas/ superpowers-laravel --skill laravel:api-resources-and-pagination安装后在 Claude Code 中输入/laravel:api-resources-and-pagination确认已加载。
详细介绍
API 资源与分页
通过资源表示模型;不要让传输层关注点渗入 Eloquent。
命令
# Resource
sail artisan make:resource PostResource # or: php artisan make:resource PostResource
# Controller usage
return PostResource::collection(
Post::with('author')->latest()->paginate(20)
);
# Resource class
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'author' => new UserResource($this->whenLoaded('author')),
'published_at' => optional($this->published_at)->toAtomString(),
];
}
模式
- 优先使用
Resource::collection($query->paginate()),而不是手动构造数组 - 使用
when()/mergeWhen()添加条件字段 - 为客户端保留分页游标/链接
- 契约变更时为资源添加版本;避免悄然破坏字段
Laravel 13+:JSON:API 资源
一方提供的 JSON:API 资源可处理资源对象(type/id/attributes/relationships)、?include= 关系包含、?fields[...]= 稀疏字段集、链接和 application/vnd.api+json 标头。
class PostJsonApiResource extends JsonApiResource
{
public function toArray($request)
{
return [
'type' => 'posts',
'id' => $this->id,
'attributes' => ['title' => $this->title, 'body' => $this->body],
'relationships' => ['author' => new UserJsonApiResource($this->author)],
];
}
}
- 当客户端需要遵循规范时(如 Ember、JSON:API 工具),请使用 JSON:API 资源;其他情况下,普通资源也完全够用
- 不要在普通资源之上手动实现
included/稀疏字段集逻辑——请使用一方提供的类
评论
支持 Markdown