$npx skillfedfor your agent

laravel-api-resource-patterns

Learn how to structure Laravel API Resources for clean model transformation and consistent JSON responses. This skill covers conditional attributes, relationship loading, collections with pagination, and techniques to prevent N+1 queries.

Laravel API Resource Patterns teaches best practices for transforming Eloquent models into structured JSON responses.

AI-generated summary based on this skill's SKILL.md

41 8 MITupdated by iSerter

Decision gist · record as of 2026-04-19

Laravel API Resource Patterns teaches best practices for transforming Eloquent models into structured JSON responses. Learn how to structure Laravel API Resources for clean model transformation and consistent JSON responses. This skill covers conditional attributes, relationship loading, collections with pagination, and techniques to prevent N+1 queries.

manual: git clone https://github.com/iSerter/laravel-claude-agents → cp -r laravel-claude-agents/skills/laravel-api-resource-patterns ~/.claude/skills/laravel-api-resource-patterns
skills/laravel-api-resource-patterns/SKILL.md · version 40a60aa9

Use it when

  • laravel-api-resource-patterns covers using whenLoaded() to safely include relationship data only when it's already loaded on the model.
  • laravel-api-resource-patterns explains conditional attribute inclusion through methods like when() and whenLoaded().

Verify before relying

Read SKILL.md below before installing (1 file). Open directory: indexed for reading, not audited.

Same gist for agents: .md · .json

Install

iSerter/laravel-claude-agents/laravel-api-resource-patterns · repository language: PHP

Open directory. Skills are indexed for reading, not audited. Review a skill's body before installing it.

Frequently asked questions

AI-generated answers based on this skill's SKILL.md and metadata

What are laravel api resource best practices?

laravel-api-resource-patterns teaches you to structure API Resources for clean, consistent JSON responses. Best practices include using whenLoaded() to prevent N+1 queries, defining conditional attributes for flexible responses, properly loading relationships before transformation, and organizing collections with pagination metadata. Resources act as a transformation layer between your models and API output.

How do you prevent N+1 queries using whenLoaded in resources?

laravel-api-resource-patterns covers using whenLoaded() to safely include relationship data only when it's already loaded on the model. This prevents the resource from triggering additional queries. Load relationships eagerly in your controller (e.g., User::with('posts')->get()), then in your Resource class use $this->whenLoaded('posts') to conditionally include them without extra database hits.

How can laravel resources transform models to JSON with conditional attributes?

laravel-api-resource-patterns explains conditional attribute inclusion through methods like when() and whenLoaded(). Define fields that appear only under certain conditions—for example, showing admin-only fields only to authenticated admins, or including timestamps only when requested. This keeps your API responses flexible and secure without duplicating resource classes.

How do you handle pagination and relationships in laravel resource collections?

laravel-api-resource-patterns demonstrates wrapping paginated results in ResourceCollections, which preserve pagination metadata (current_page, total, etc.) alongside your transformed data. Load relationships before passing to the collection, use whenLoaded() for optional includes, and leverage the collection's meta() method to attach custom metadata like links or filtering info.

What is the purpose of laravel resource wrapping and unwrapping?

laravel-api-resource-patterns covers resource wrapping—automatically nesting your data under a key (e.g., 'data')—and unwrapping to return raw arrays. Wrapping provides consistent envelope structure for collections and error responses; unwrapping simplifies single-resource endpoints. Control this via config or the resource's wrap() method to match your API design.

How do you structure RESTful API responses with links and metadata?

laravel-api-resource-patterns shows adding HATEOAS links and metadata to resources via the with() method and custom toArray() logic. Include self links, related resource links, and pagination links in collections. Attach metadata like total counts, filtering info, or API version. This makes your API self-documenting and easier for clients to navigate.

SKILL.md

Rendered from the published skill. Quoted content, verbatim.

API Resource Patterns

Basic Resource Structure

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'created_at' => $this->created_at->toISOString(),
            'updated_at' => $this->updated_at->toISOString(),
        ];
    }
}

Conditional Attributes

```php public function toArray($request): array { return [ 'id' => $this->id, 'title' => $this->title,

    // Only include if loaded
    'author' => new UserResource($this->whenLoaded('user')),

    // Only include if condition is true
    'content' => $this->when($request->user()?->can('view', $this->resource), $this->content),

    // Only include if not null

(truncated - see the full file via the links below)

File tree — 1 file
skills/laravel-api-resource-patterns/SKILL.md

Let your AI agent find skills like this

Example. Real query, live index.

You found this page by searching. An agent finds it by wishing: SkillFed indexes 56,283 agent skills by what they can do, searchable in plain language.

wish › “Learn Laravel API Resource best practices and patterns”

Give your agent the search over MCP, or paste the wish link into any chat. No install? Search from any chat →

Related skills

Laravel
by rawveg · rawveg/skillsforge-marketplace

Get expert guidance on Laravel 12.x application development, from foundational concepts like routing and database migrations to advanced patterns including Eloquent relationships, API design, and authentication with Sanctum. This skill covers the full development lifecycle—models, validation, queues, dependency injection, and best practices for building scalable web applications.

no license declared → metadata onlyupdated Feb 2026
★ 39repo stars
php-expert
by personamanagmentlayer · personamanagmentlayer/pcl

PHP Expert provides in-depth instruction on PHP 8+ language features including union types, named arguments, match expressions, attributes, and enums. Learn Laravel framework patterns, Composer dependency management, and object-oriented design principles for building robust applications.

Apache-2.0updated Mar 2026
★ 38repo stars
laravel-specialist
by Jeffallan · Jeffallan/claude-skills

Laravel Specialist guides you through building production-ready Laravel 10+ applications with type-safe Eloquent models, queue workers, API resources, and Livewire components. It enforces modern PHP 8.2+ patterns, eager loading, dependency injection, and >85% test coverage across feature and unit tests. Use it for architecting database schemas, implementing authentication flows, optimizing queries, and validating code against PSR-12 standards.

MITupdated May 2026
★ 10,759repo stars
laravel-middleware-patterns
by iSerter · iSerter/laravel-claude-agents

This skill teaches Laravel middleware architecture through practical patterns for request handling. Learn to build before and after middleware, implement terminable patterns for post-response tasks, organize middleware into groups, pass parameters to middleware, and apply common patterns like rate limiting, locale handling, and tenant scoping.

MITupdated Apr 2026
★ 41repo stars
laravel-api
by JustSteveKing · JustSteveKing/laravel-api-skill

Laravel API guides you through building REST APIs using stateless, resource-scoped architecture with explicit boundaries between HTTP, business logic, and data layers. It enforces PSR-12 code quality, JWT authentication, versioned endpoints, and invokable controllers to establish maintainable patterns from your first resource.

MITupdated Jan 2026
★ 26repo stars
laravel-authorization-patterns
by iSerter · iSerter/laravel-claude-agents

Learn to implement authorization in Laravel using Gates for general ability checks and Policies for model-specific access rules. This skill covers middleware integration, Blade directives for conditional rendering, and Response objects for detailed permission messages. Includes testing strategies and best practices for securing controllers and form requests.

MITupdated Apr 2026
★ 41repo stars

More skills laravel-best-practices (MIT)

Tags
json-transformationeager-loadingpagination-metadatahateoas-linksresponse-formattingquery-optimizationconditional-fieldsrest-api-designrelationship-handlingdata-serialization