mcpField
L
laravel:api-resources-and-pagination

laravel:api-resources-and-pagination

github.com/jpcaparasDevelopment157144 installsUpdated 18w ago
Repository

About laravel:api-resources-and-pagination

A Laravel development skill for shaping API responses with Resources and pagination. It covers conditional fields, preserving pagination metadata, versioning response contracts, and first-party JSON:API Resources.

Key features

  1. 01Model representation with Resources
  2. 02Conditional fields with when() and mergeWhen()
  3. 03Preserving pagination links and cursors
  4. 04Versioning API resource contracts
  5. 05JSON:API resource patterns

Use cases

  1. 01Building paginated Laravel endpoints
  2. 02Returning conditional response fields
  3. 03Supporting JSON:API clients
  4. 04Changing API response contracts

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/jpcaparas/superpowers-laravel --skill laravel:api-resources-and-pagination

After installing, type/laravel:api-resources-and-paginationin Claude Code to confirm it loaded.

Details

From the project README

API Resources and Pagination

Represent models via Resources; keep transport concerns out of Eloquent.

Commands

# 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(),
    ];
}

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

Laravel 13+: JSON:API Resources

First-party JSON:API resources handle resource objects (type/id/attributes/relationships), ?include= relationship inclusion, ?fields[...]= sparse fieldsets, links, and application/vnd.api+json headers.

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)],
        ];
    }
}
  • Reach for JSON:API resources when clients need the spec (Ember, JSON:API tooling); plain Resources remain fine otherwise
  • Don't hand-roll included/sparse-fieldset logic on top of plain Resources — use the first-party classes

Comments

Markdown supported