Authorize records and avoid N+1 queries
Protect ownership and fetch related data deliberately.
Scope before retrieving
A record ID from a URL is untrusted input. Fetch through a user-scoped relationship or authorize the loaded record before returning it. A missing record and another user's private record may both return 404 to avoid revealing that the record exists. Apply the same rule to edit, export, and download actions.
Spot N+1 behavior
A list that loads 30 records and then accesses each record's owner can trigger 31 queries. Eager-load the relationship when the page needs it, and select only relationships actually used. Query counts are useful evidence, but first confirm that the displayed data is correct and authorized.
$orders = $request->user()->orders()
->with(['items.product'])
->latest()
->paginate(20);
Test both risks
Create records for two users and assert that each can read only their own. Then render a page with several related records and confirm query growth stays bounded. A test that checks only a single record will miss an N+1 issue, while a query-count test without two users can miss the privacy issue.
Check your understanding
Does eager loading make an unscoped query safe?
Show explanation
No. It reduces extra queries; ownership still needs a scoped query or an authorization policy.
You can read for free. Create an account to save your progress.
← Previous lesson: Make related writes atomic Next lesson: Design a job that can safely retry →Put this lesson into practice
A practice activity at this level in the same module.
Try: Find customers with no ordersFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.