Eloquent relationship properties may issue database queries when accessed, so a template that displays a relation for each case can turn one queue query into many. Eager loading requests needed relations with the parent query and prevents those per-row lookups. That is not a license to load every attachment for every case. A reviewer queue must first restrict rows to the caller, then choose the fields and relation summaries shown on one page. Cursor pagination uses ordered values to continue through large results without walking an ever-growing offset. Its order needs a unique tie breaker and database support from suitable indexes; it cannot promise an exact numbered page count.
Laravel Eloquent Loading and Cursor Page Cost
Working case
A municipal queue renders 47 permits with district names and attachment counts. The first implementation fetches permits and lazily reads each district and attachments collection. Query count rises with the page. The second eagerly loads every attachment for 47,000 permits to silence the query counter and strains memory. A third uses an offset near the end of the queue; response width is small, yet the database spends time skipping earlier rows. The repaired query scopes by reviewer, selects a 47-row cursor page, eager loads the one district name actually rendered, obtains attachment counts without loading all attachment models, and orders by created_at plus a unique case ID.
Implementation boundary
<?php
use App\Models\PermitCase;
$queue = PermitCase::query()
->whereHas('reviewers', fn ($reviewers) => $reviewers->whereKey($reviewer->id))
->with('district:id,name')
->withCount('attachments')
->orderByDesc('created_at')
->orderByDesc('id')
->cursorPaginate(47);Start with the authorization predicate in the SQL builder; do not filter another reviewer's cases in PHP after reading them. Use with for the displayed district relation and withCount for attachment totals when the actual attachment records are not shown. Order by a non-null creation field and ID, then cursorPaginate the fixed page width. Include foreign keys needed by selected relations and avoid selecting so few columns that hydration triggers unexpected work. Cursor values must remain part of the same reviewer-scoped query; a client cursor is navigation state, not permission. Where a screen needs numbered pages and totals, choose another pagination contract and accept its count and offset costs deliberately.
Cost and boundaries
A bounded page uses O(page size) parent memory, plus only the selected related district rows. withCount adds SQL work but avoids materializing every attachment. Eager loading a many-valued relation can still transfer thousands of children, so measure row count and payload size as well as query count. Offset pagination can spend work proportional to the skipped rows; an indexed cursor often improves deep continuation. A cursor does not provide a cheap exact total or stable page number, and inserts can change what appears between requests. Track database plan, p95 latency, query count, transferred bytes, and memory for both sparse and attachment-heavy cases.
Failure trace
Seed 47 cases with repeated created_at values and verify ID ordering traverses without duplicates. Add a case with hundreds of attachments; the list must display its count without hydrating those records. Remove eager loading and inspect the N+1 queries produced by district access, then restore it. Try a deep offset on a large fixture and compare its query plan with cursor continuation. Submit a cursor while changing reviewer identity and ensure the SQL permission predicate still applies. Ask a list serializer for a relation it did not preload and catch the lazy load in a controlled test before that behavior reaches production.
Verification
- The reviewer filter remains on every page.
- Attachment counts do not load attachment models.
- Timestamp ties are broken by a unique case ID.
Practice drill
Build a reviewer queue with district labels, attachment totals, and a 47-case page limit. Instrument query count and SQL time before optimization. Add the reviewer scope in the query, then with and withCount only for displayed data. Give several cases the same timestamp, add an ID tie breaker, and implement next-page navigation. Compare cursor and offset behavior at a deep position with an index on the chosen order. Remove an eager load in a negative test and show the query count change. Explain whether the product truly needs an exact total or numbered page links.
Decision note
Scope the data first, then optimize the bounded response for both query count and transferred rows.
Common Mistakes
- Fixing N+1 by loading an unbounded result set.
- Assuming a deep offset costs only 47 rows.
- Using a cursor order without a unique tie breaker.
Related lessons
Laravel Policy, Query, and Queue Boundaries; Laravel Route Binding, Policy, and Private Resource Scope; Laravel Form Requests, Transactions, and Approval Replay; Laravel After-Commit Jobs and Outbox Recovery; Data Persistence; Django QuerySet Shape, Prefetch, and Page Cost.
Apply and check
Build Project: Laravel permit review workflow and review Web Development: Laravel policy, query, and queue quiz.
