laravel-api-resources-and-pagination

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Resources and Pagination

API Resources 与分页

Represent models via Resources; keep transport concerns out of Eloquent.
通过 Resources 表示模型,将传输层相关逻辑从 Eloquent 中剥离。

Commands

命令

undefined
undefined

Resource

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(), ]; }
undefined
public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'author' => new UserResource($this->whenLoaded('author')), 'published_at' => optional($this->published_at)->toAtomString(), ]; }
undefined

Patterns

使用规范

  • Prefer
    Resource::collection($query->paginate())
    over manual arrays
  • Use
    when()
    /
    mergeWhen()
    for conditional fields
  • Keep pagination cursors/links intact for clients
  • Version resources when contracts change; avoid breaking fields silently
  • 优先使用
    Resource::collection($query->paginate())
    而非手动构造数组
  • 使用
    when()
    /
    mergeWhen()
    实现条件字段
  • 为客户端保留完整的分页游标/链接
  • 当接口契约变更时对 Resources 进行版本控制,避免无感知地破坏字段结构