Laravel API Resources: Fieldsets, Relations &amp; Versioning | Mohamed Said       [Skip to content](#main)  [ ![](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png) Mohamed SaidLaravel Backend Engineer ](https://www.msaied.com/public) - [Home](https://www.msaied.com/public)
- [Projects](https://www.msaied.com/public/projects)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [About](https://www.msaied.com/public#about)

           [  Contact](https://www.msaied.com/public#contact) Menu 

Menu
----

Close 

 - [HomeStart here](https://www.msaied.com/public)
- [ProjectsCase studies](https://www.msaied.com/public/projects)
- [ArticlesEngineering notes](https://www.msaied.com/public/articles)
- [CertificatesCredentials](https://www.msaied.com/public/certificates)
- [AboutHow I work](https://www.msaied.com/public#about)
- [ContactGet in touch](https://www.msaied.com/public#contact)

  [Start a conversation](https://www.msaied.com/public#contact) [WhatsApp](https://wa.me/201094619204) [Email](mailto:hello@msaied.com) 

 1. [Home](https://www.msaied.com/public)
2. /
3. [Articles](https://www.msaied.com/public/articles)
4. /
5. Laravel API Resources: Sparse Fieldsets, Conditional Relationships, and Versioning

 Laravel API Resources: Sparse Fieldsets, Conditional Relationships, and Versioning
===================================================================================

 Go beyond basic API resources. Learn how to implement sparse fieldsets, conditionally load relationships, and version your JSON API responses cleanly in Laravel without bloating your resource classes.

 ![](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp) [Mohamed Said](https://www.msaied.com/public#person) Published 1 Jul 2026 · Updated 1 Jul 2026 · 3 min read

ShareCopy linkCopied

 ![Laravel API Resources: Sparse Fieldsets, Conditional Relationships, and Versioning](https://cdn.msaied.com/336/89d518450335e8fcdaa5be882cf4dd3e.png) 

  On this page +1. [Beyond toArray: Making API Resources Do Real Work](#beyond-codetoarraycode-making-api-resources-do-real-work)
2. [Sparse Fieldsets Without a Package](#sparse-fieldsets-without-a-package)
3. [Conditional Relationship Loading](#conditional-relationship-loading)
4. [Clean API Versioning Without Route Duplication](#clean-api-versioning-without-route-duplication)
5. [Key Takeaways](#key-takeaways)

 Beyond `toArray`: Making API Resources Do Real Work
---------------------------------------------------

Laravel's `JsonResource` class is deceptively simple. Most teams use it as a glorified array cast, but it carries enough power to handle sparse fieldsets, conditional relationship loading, and multi-version response contracts — without reaching for a dedicated API layer package.

---

### Sparse Fieldsets Without a Package

JSON:API specifies that clients can request only the fields they need via `?fields[articles]=title,body`. Implementing this in a resource is straightforward once you centralise the parsing.

```php
// app/Http/Resources/Concerns/SparseFieldset.php
trait SparseFieldset
{
    protected function allowed(string $type, array $fields): array
    {
        $requested = request()
            ->input("fields.{$type}");

        if (! $requested) {
            return $fields;
        }

        $keys = array_flip(explode(',', $requested));

        return array_intersect_key($fields, $keys);
    }
}

```

```php
// app/Http/Resources/ArticleResource.php
class ArticleResource extends JsonResource
{
    use SparseFieldset;

    public function toArray(Request $request): array
    {
        return $this->allowed('articles', [
            'id'         => $this->id,
            'title'      => $this->title,
            'body'       => $this->body,
            'created_at' => $this->created_at,
        ]);
    }
}

```

The `allowed()` helper filters the field map to only what the client requested. No extra dependencies, no magic.

---

### Conditional Relationship Loading

The built-in `whenLoaded()` is good, but it only checks whether the relation is already eager-loaded. For APIs that accept an `?include=` parameter, you want to drive eager loading from the resource itself rather than the controller.

```php
// app/Http/Resources/ArticleResource.php
public function with(Request $request): array
{
    return [];
}

public function toArray(Request $request): array
{
    return [
        'id'     => $this->id,
        'title'  => $this->title,
        'author' => $this->whenLoaded('author', fn () =>
            new UserResource($this->author)
        ),
        'tags'   => $this->whenLoaded('tags', fn () =>
            TagResource::collection($this->tags)
        ),
    ];
}

```

In the controller, parse `?include=` once and eager-load accordingly:

```php
// app/Http/Controllers/ArticleController.php
public function show(Article $article): ArticleResource
{
    $includes = array_intersect(
        explode(',', request()->input('include', '')),
        ['author', 'tags'] // allowlist
    );

    return new ArticleResource(
        $article->loadMissing($includes)
    );
}

```

This keeps the allowlist in the controller (where auth context lives) and the shape in the resource.

---

### Clean API Versioning Without Route Duplication

The temptation is to create `V1\ArticleResource` and `V2\ArticleResource` as entirely separate files. That leads to drift. A better pattern: a single resource class that branches on a version header or route prefix.

```php
// app/Http/Resources/ArticleResource.php
public function toArray(Request $request): array
{
    $version = $request->header('X-API-Version', 'v1');

    return match ($version) {
        'v2'    => $this->v2Fields(),
        default => $this->v1Fields(),
    };
}

private function v1Fields(): array
{
    return [
        'id'    => $this->id,
        'title' => $this->title,
    ];
}

private function v2Fields(): array
{
    return [
        'id'       => $this->id,
        'title'    => $this->title,
        'slug'     => $this->slug,
        'metadata' => $this->metadata,
    ];
}

```

When v1 is retired, delete `v1Fields()` and the `match` arm. No orphaned route files, no duplicated middleware stacks.

For larger APIs where versions diverge significantly, namespace the resource classes but share a base:

```php
// app/Http/Resources/V2/ArticleResource.php
class ArticleResource extends \App\Http\Resources\ArticleResource
{
    public function toArray(Request $request): array
    {
        return array_merge(parent::toArray($request), [
            'slug' => $this->slug,
        ]);
    }
}

```

Inheritance is fine here — the relationship is genuinely "is-a".

---

### Key Takeaways

- **Sparse fieldsets** can be implemented with a single trait and `array_intersect_key` — no package needed.
- **Conditional includes** belong in the controller (allowlist) and the resource (`whenLoaded`); never auto-load in the resource.
- **Version branching** inside one resource class is maintainable for minor divergence; namespace inheritance works for major breaks.
- Keep resources focused on *shape*, not business logic — computed values belong in model accessors or dedicated DTOs.
- Always test resources with `ArticleResource::make($model)->toArray(request())` in Pest; it's fast and catches regressions early.

- [laravel](https://www.msaied.com/public/articles?search=laravel)
- [api](https://www.msaied.com/public/articles?search=api)
- [resources](https://www.msaied.com/public/articles?search=resources)
- [versioning](https://www.msaied.com/public/articles?search=versioning)

 Frequently asked questions 
---------------------------

  Should I implement sparse fieldsets manually or use a JSON:API package like spatie/laravel-json-api-paginate?For full JSON:API compliance (type objects, links, meta) a package is worth it. For a simpler REST API that just wants field filtering, the trait approach shown here avoids the overhead and keeps your resource shape under your control.

   Is it safe to branch on a request header inside a resource's toArray method?Yes, but inject the version via the constructor if you want the resource to be testable without a real HTTP request. Pass `$version` in and store it as a property — that makes unit testing each version branch trivial.

   How do I handle pagination with sparse fieldsets in a collection resource?The fieldset trait works per-item because each resource instance calls allowed() independently. ResourceCollection wraps the items, so pagination metadata is unaffected. Just ensure your collection class calls the item resource, not a raw array map.

   ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)About the author
----------------

[Mohamed Said](https://www.msaied.com/public#person)Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

[About](https://www.msaied.com/public#about) [GitHub ↗](https://github.com/EG-Mohamed) [LinkedIn ↗](https://www.linkedin.com/in/msaiedm/) [WhatsApp ↗](https://wa.me/201094619204) [Email Address ↗](mailto:hello@msaied.com) [My CV ↗](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)  

   [Previous articleLaravel WebSocket Broadcasting with Reverb: Scaling Beyond a Single Worker](https://www.msaied.com/public/articles/laravel-websocket-broadcasting-with-reverb-scaling-beyond-a-single-worker) [Next articleLaravel 12: Structured Route Files, Slim Skeletons, and the New Application Bootstrapping](https://www.msaied.com/public/articles/laravel-12-structured-route-files-slim-skeletons-and-the-new-application-bootstrapping)  

   On this page
-------------

1. [Beyond toArray: Making API Resources Do Real Work](#beyond-codetoarraycode-making-api-resources-do-real-work)
2. [Sparse Fieldsets Without a Package](#sparse-fieldsets-without-a-package)
3. [Conditional Relationship Loading](#conditional-relationship-loading)
4. [Clean API Versioning Without Route Duplication](#clean-api-versioning-without-route-duplication)
5. [Key Takeaways](#key-takeaways)

 ###  Have a technical challenge?

 Tell me what you’re building. I reply within two working days.

[Start a conversation](https://www.msaied.com/public#contact) 

   Related articles
-----------------

 [ ![](https://cdn.msaied.com/740/cce86edc21eddcbdd2f2454fadaf9c70.png)  · 3 min read### The Pipeline Pattern in Laravel: Custom Pipelines Beyond Middleware

5 Oct 2026 ](https://www.msaied.com/public/articles/the-pipeline-pattern-in-laravel-custom-pipelines-beyond-middleware-1) [ ![](https://cdn.msaied.com/739/2d6897fdcdcf090613f96f72a64b8a78.png)  · 4 min read### MySQL Full-Text Search in Laravel: Indexes, Relevance Scoring, and Boolean Mode

4 Oct 2026 ](https://www.msaied.com/public/articles/mysql-full-text-search-in-laravel-indexes-relevance-scoring-and-boolean-mode) [ ![](https://cdn.msaied.com/738/073696a3fefe18bec825beec5ac658f5.png)  · 4 min read### Laravel Queue Rate-Limited Middleware: Throttling Jobs Without Losing Work

4 Oct 2026 ](https://www.msaied.com/public/articles/laravel-queue-rate-limited-middleware-throttling-jobs-without-losing-work) 

  Have a technical challenge?
----------------------------

Tell me what you’re building. I reply within two working days.

 [Discuss your project ↗](https://www.msaied.com/public#contact) 

  © 2026 Mohamed Said · Built with Laravel, meant to last.Senior Backend Engineer specializing in Laravel, scalable SaaS platforms, APIs, and cloud infrastructure. I build secure, high-performance web applications that help businesses grow.

 - [Home](https://www.msaied.com/public)
- [Articles](https://www.msaied.com/public/articles)
- [Certificates](https://www.msaied.com/public/certificates)
- [GitHub](https://github.com/EG-Mohamed)
- [LinkedIn](https://www.linkedin.com/in/msaiedm/)
- [WhatsApp](https://wa.me/201094619204)
- [Email Address](mailto:hello@msaied.com)
- [My CV](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
- [Sitemap](https://www.msaied.com/public/sitemap.xml)
