laravel-api-resources-and-pagination
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Resources and Pagination
API Resources 与分页
Represent models via Resources; keep transport concerns out of Eloquent.
通过 Resources 表示模型,将传输层相关逻辑从 Eloquent 中剥离。
Commands
命令
undefinedundefinedResource
Resource
php artisan make:resource PostResource # or: php artisan make:resource PostResource
php artisan make:resource PostResource # or: php artisan make:resource PostResource
Controller usage
Controller usage
return PostResource::collection(
Post::with('author')->latest()->paginate(20)
);
return PostResource::collection(
Post::with('author')->latest()->paginate(20)
);
Resource class
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(),
];
}
undefinedpublic function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'author' => new UserResource($this->whenLoaded('author')),
'published_at' => optional($this->published_at)->toAtomString(),
];
}
undefinedPatterns
使用规范
- Prefer over manual arrays
Resource::collection($query->paginate()) - Use /
when()for conditional fieldsmergeWhen() - Keep pagination cursors/links intact for clients
- Version resources when contracts change; avoid breaking fields silently
- 优先使用 而非手动构造数组
Resource::collection($query->paginate()) - 使用 /
when()实现条件字段mergeWhen() - 为客户端保留完整的分页游标/链接
- 当接口契约变更时对 Resources 进行版本控制,避免无感知地破坏字段结构