php
39 lines · 9 steps
Eager loading without N+1 in Laravel
A Laravel controller fetches posts with curated relations, counts, and conditional filters in a single efficient query batch.
Explained by
highlit
1class PostController extends Controller
2{
3 public function index(Request $request)
4 {
5 $posts = Post::query()
6 ->with([
7 'author:id,name,avatar_url',
8 'category:id,name,slug',
9 'tags:id,name',
10 'comments' => fn ($query) => $query
11 ->approved()
12 ->latest()
13 ->limit(5),
14 'comments.author:id,name',
15 ])
16 ->withCount(['comments', 'likes'])
17 ->when($request->filled('category'), function ($query) use ($request) {
18 $query->whereHas('category', fn ($q) => $q->where('slug', $request->category));
19 })
20 ->published()
21 ->latest('published_at')
22 ->paginate(15)
23 ->withQueryString();
24
25 return PostResource::collection($posts);
26 }
27
28 public function show(Post $post)
29 {
30 $post->load([
31 'author.profile',
32 'category.parent',
33 'comments' => fn ($query) => $query->approved()->with('author:id,name')->latest(),
34 'media',
35 ])->loadCount('likes');
36
37 return new PostResource($post);
38 }
39}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Eager loading related models with `with` collapses what would be many lazy queries into a handful of batched ones.
- 2Selecting specific columns and constraining nested relations keeps payloads lean and queries fast.
- 3`when` lets you bolt conditional filters onto a query chain without breaking it into branching if statements.
Related explainers
php
<?php namespace App\Support;
Locale-aware formatting with PHP's intl extension
internationalization
encapsulation
constructor-injection
Intermediate
7 steps
javascript
const express = require('express'); const v1 = express.Router();
Versioning an API with Express Routers
api versioning
routing
modularity
Intermediate
10 steps
php
<?php namespace App\Support;
Merging query params onto a URL in PHP
url-parsing
query-strings
immutability
Intermediate
8 steps
python
import csv import io from datetime import datetime
Streaming a CSV export in Flask
streaming
generators
csv
Intermediate
9 steps
php
<?php class ImageUploadService {
Validating file uploads safely in PHP
file-upload
input-validation
security
Intermediate
8 steps
php
<?php namespace App\View;
Building a safe HTML escaper in PHP
security
xss
escaping
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/eager-loading-without-n-1-in-laravel-explained-php-551b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.