Laravel API Resources: Sparse Fieldsets &amp; Cursor Pagination | Mohamed Said        [  ![Mohamed Said](https://cdn.msaied.com/01KT78WE565VEMM3PSNQAAB0MH.png)   Mohamed Said Laravel Backend Engineer  ](https://www.msaied.com) [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles  ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

       [  ](https://github.com/EG-Mohamed)       

 [ Home ](https://www.msaied.com) [ Projects ](https://www.msaied.com/projects) [ Articles ](https://www.msaied.com/articles) [ Certificates ](https://www.msaied.com/certificates) [ Contact ](https://www.msaied.com#contact-section) 

  [ home ](https://www.msaied.com)    [ articles ](https://www.msaied.com/articles)    Laravel API Resources: Sparse Fieldsets, Conditional Relationships, and Cursor Pagination        On this page       1. [  Beyond Basic JsonResource ](#beyond-basic-jsonresource)
2. [  Sparse Fieldsets ](#sparse-fieldsets)
3. [  Conditional Relationships Without N+1 ](#conditional-relationships-without-n1)
4. [  Nested Conditional Data ](#nested-conditional-data)
5. [  Cursor Pagination at Scale ](#cursor-pagination-at-scale)
6. [  Exposing Pagination Links in Resources ](#exposing-pagination-links-in-resources)
7. [  Takeaways ](#takeaways)

  ![Laravel API Resources: Sparse Fieldsets, Conditional Relationships, and Cursor Pagination](https://cdn.msaied.com/710/4f310773d50e6b3a7ab53e64d3e76921.png)

  #laravel   #api   #eloquent   #performance  

 Laravel API Resources: Sparse Fieldsets, Conditional Relationships, and Cursor Pagination 
===========================================================================================

     27 Sep 2026      3 min read    ![Mohamed Said](https://cdn.msaied.com/01M22N44A70A5MC2S599JP0MPH.webp)  Mohamed Said  

       Table of contents

1. [  01   Beyond Basic JsonResource  ](#beyond-basic-jsonresource)
2. [  02   Sparse Fieldsets  ](#sparse-fieldsets)
3. [  03   Conditional Relationships Without N+1  ](#conditional-relationships-without-n1)
4. [  04   Nested Conditional Data  ](#nested-conditional-data)
5. [  05   Cursor Pagination at Scale  ](#cursor-pagination-at-scale)
6. [  06   Exposing Pagination Links in Resources  ](#exposing-pagination-links-in-resources)
7. [  07   Takeaways  ](#takeaways)

 Beyond Basic JsonResource
-------------------------

Most Laravel APIs start with a `JsonResource` that dumps every column and calls it a day. That works until clients complain about payload size, mobile teams beg for field filtering, and your DBA notices the missing indexes on `OFFSET`-based pagination. This article tackles all three with concrete, production-ready patterns.

---

Sparse Fieldsets
----------------

Sparse fieldsets let clients request only the columns they need — a pattern borrowed from JSON:API. Implement it cleanly by reading a `fields` query parameter inside your resource.

```php
// app/Http/Resources/PostResource.php
class PostResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $fields = $this->requestedFields($request, 'posts');

        $all = [
            'id'         => $this->id,
            'title'      => $this->title,
            'body'       => $this->body,
            'created_at' => $this->created_at->toIso8601String(),
            'author'     => new UserResource($this->whenLoaded('author')),
        ];

        return $fields ? array_intersect_key($all, array_flip($fields)) : $all;
    }

    private function requestedFields(Request $request, string $type): array
    {
        $raw = $request->query('fields', []);
        if (is_string($raw)) {
            return [];
        }
        return array_map('trim', explode(',', $raw[$type] ?? ''));
    }
}

```

A request like `GET /posts?fields[posts]=id,title` now returns only those two keys. Keep the logic in a `HasSparseFieldsets` trait if you need it across many resources.

---

Conditional Relationships Without N+1
-------------------------------------

`whenLoaded()` is the correct primitive, but the real trap is forgetting to eager-load based on what the client actually requested.

```php
// app/Http/Controllers/PostController.php
public function index(Request $request): AnonymousResourceCollection
{
    $includes = array_filter(
        explode(',', $request->query('include', '')),
        fn(string $rel) => in_array($rel, ['author', 'tags', 'comments'], true)
    );

    $posts = Post::query()
        ->with($includes)          // only load what was asked for
        ->cursorPaginate(25);

    return PostResource::collection($posts);
}

```

Whitelisting allowed includes server-side prevents clients from triggering arbitrary eager loads. Pair this with `whenLoaded()` in the resource and you get zero N+1 queries regardless of which includes the client sends.

### Nested Conditional Data

For attributes that are expensive to compute, use `when()`:

```php
'read_time' => $this->when(
    $request->boolean('meta'),
    fn() => $this->computeReadTime()
),

```

The closure is only evaluated when the condition is truthy, so the computation never runs for clients that don't need it.

---

Cursor Pagination at Scale
--------------------------

`OFFSET` pagination degrades as page numbers grow because the database must scan and discard all preceding rows. Cursor pagination solves this by encoding the last-seen position in an opaque token.

```php
$posts = Post::query()
    ->orderBy('id')
    ->cursorPaginate(25);

return PostResource::collection($posts);
// Response includes:
// "next_cursor": "eyJpZCI6MTAwfQ"
// "prev_cursor": "eyJpZCI6NzZ9"

```

Laravel's `cursorPaginate()` automatically adds a `WHERE id > ?` clause using the decoded cursor, keeping the query O(1) relative to dataset size.

**One constraint:** cursor pagination requires a stable, unique sort column (or composite). Sorting by `created_at` alone breaks when two rows share the same timestamp. Add `id` as a tiebreaker:

```php
->orderBy('created_at')
->orderBy('id')
->cursorPaginate(25);

```

Laravel encodes both columns in the cursor automatically.

### Exposing Pagination Links in Resources

```php
return PostResource::collection($posts)
    ->additional([
        'links' => [
            'next' => $posts->nextPageUrl(),
            'prev' => $posts->previousPageUrl(),
        ],
    ]);

```

---

Takeaways
---------

- **Sparse fieldsets** reduce payload size and keep serialization logic in one place — use a per-type `fields` query parameter.
- **Whitelist includes** server-side before passing them to `with()`; never trust raw client input for eager loading.
- **`whenLoaded()` + `when()`** are your tools for zero-cost conditional data — lean on closures to defer expensive computation.
- **Cursor pagination** is always preferable to offset for large, append-heavy tables; ensure your sort key is unique or add a tiebreaker.
- Keep resource classes thin: move field-filtering and include-parsing logic into traits or dedicated resolver classes as the API grows.

 Found this useful?

          [  ](https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Flaravel-api-resources-sparse-fieldsets-conditional-relationships-and-cursor-pagination&text=Laravel+API+Resources%3A+Sparse+Fieldsets%2C+Conditional+Relationships%2C+and+Cursor+Pagination) [  ](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.msaied.com%2Farticles%2Flaravel-api-resources-sparse-fieldsets-conditional-relationships-and-cursor-pagination) 

 Frequently Asked Questions 
----------------------------

  3 questions  

     Q01  Can sparse fieldsets break API consumers that expect a fixed schema?        Yes, if consumers rely on every field always being present. Document the default (all fields) clearly and treat sparse fieldsets as an opt-in optimization. Consider versioning your API contract separately from the fieldset feature. 

      Q02  When should I prefer offset pagination over cursor pagination?        Offset pagination is acceptable for small, rarely-updated datasets where clients need random page access (e.g., jump to page 10). For large or frequently-inserted tables, cursor pagination is almost always the right choice. 

      Q03  How do I test that N+1 queries are not introduced when new includes are added?        Use `DB::enableQueryLog()` in a Pest test or the `assertQueryCount()` helper from the `laravel-query-detector` package. Assert the exact query count for a known set of includes so regressions surface immediately in CI. 

  Continue reading

 More Articles 
---------------

 [ View all    ](https://www.msaied.com/articles) 

 [ ![Clean Architecture Testing with Pest: Actions, Fakes, and Architectural Assertions](https://cdn.msaied.com/709/ee356004b06e38b322823a2cf5305cee.png) laravel pest testing 

### Clean Architecture Testing with Pest: Actions, Fakes, and Architectural Assertions

Learn how to test Laravel actions, DTOs, and domain services with Pest — using fakes, higher-order tests, and...

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

 27 Sep 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/clean-architecture-testing-with-pest-actions-fakes-and-architectural-assertions-1) [ ![Multi-Tenant SaaS with Laravel: Scoping Queries, Resolving Tenants, and Isolating State](https://cdn.msaied.com/708/08ce1de79b1d408fbd91c91ddcb3f056.png) laravel multi-tenancy saas 

### Multi-Tenant SaaS with Laravel: Scoping Queries, Resolving Tenants, and Isolating State

A practical deep-dive into building multi-tenant SaaS with Laravel — covering tenant resolution middleware, au...

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

 27 Sep 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/multi-tenant-saas-with-laravel-scoping-queries-resolving-tenants-and-isolating-state) [ ![Livewire v3 Internals: Morph Markers, JS Hooks, and Alpine Integration](https://cdn.msaied.com/707/0eb21e520c1216424fd97efe3608f4db.png) livewire laravel alpine 

### Livewire v3 Internals: Morph Markers, JS Hooks, and Alpine Integration

Go beyond the docs: understand how Livewire v3 diffs and patches the DOM with morph markers, intercept the lif...

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

 27 Sep 2026     3 min read  

  Read    

 ](https://www.msaied.com/articles/livewire-v3-internals-morph-markers-js-hooks-and-alpine-integration-5) 

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

Explore

- [Home](https://www.msaied.com)
- [Projects](https://www.msaied.com/projects)
- [Articles](https://www.msaied.com/articles)
- [Certificates](https://www.msaied.com/certificates)
- [Contact](https://www.msaied.com#contact-section)

Connect

- [   hello@msaied.com ](mailto:hello@msaied.com)
- [   +20 109 461 9204 ](tel:+201094619204)

© 2026 Mohamed Said. All rights reserved.

 [  ](https://github.com/EG-Mohamed) [  ](https://www.linkedin.com/in/msaiedm/) [  ](https://wa.me/201094619204) [  ](mailto:hello@msaied.com) [  ](https://drive.google.com/file/u/0/d/1MF20IPRJyzfy32mhEutjL5EpSls0w2Q8/view)
