mcpField
L
laravel:api-resources-and-pagination

laravel:api-resources-and-pagination

github.com/jpcaparas開発157144 回インストール18 週間前に更新
リポジトリ

laravel:api-resources-and-pagination について

Laravel API のレスポンスを Resources とページネーションで構成するスキルです。条件付きフィールド、ページネーション情報の保持、レスポンス契約のバージョン管理、標準の JSON:API Resources を扱います。

主な機能

  1. 01Resources によるモデル表現
  2. 02when() と mergeWhen() による条件付きフィールド
  3. 03ページネーションのリンクとカーソル保持
  4. 04API Resource 契約のバージョン管理
  5. 05JSON:API Resource のパターン

活用シーン

  1. 01Laravel のページネーション付きエンドポイント構築
  2. 02条件付きレスポンスフィールドの返却
  3. 03JSON:API クライアントへの対応
  4. 04API レスポンス契約の変更

インストール

コマンドをコピーしてターミナルで実行します。

$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 リソースを使用し、それ以外の場合は通常の Resources でも問題ありません
  • 通常の Resources に included /スパースフィールドセットのロジックを独自実装しないでください。ファーストパーティのクラスを使用します

コメント