TechnicalEloquent performance

Eloquent performanceLesson 2 of 28

Minimize Memory Usage

Fetch only what you show. It matters most on lists, exports and anything touching many rows.

1 min readIntermediateLesson

Eloquent performance02

The problem

A blog archive used about 20 MB of memory. select * was loading every column, including the large post body the page never shows.

The fix

Only select the columns the page actually uses, on the main query and on eager loads.

✕ Instead of this

Post::with('author')
    ->latest('published_at')
    ->get();
// select * : every column, including the large body

✓ Do this

Post::select('id', 'title', 'slug', 'published_at', 'author_id')
    ->with('author:id,name')
    ->latest('published_at')
    ->get();

The benefit

Memory drops to roughly what an empty Laravel page uses, because the big body column never leaves the database.

Results

Memory

19.8 MB4.35 MB

78% lower

A bare Laravel page uses ~4 MB

Watch out

  • Always include id. Eloquent relies on the primary key.
  • Include foreign keys that eager loads need (here author_id), or the relation comes back empty.

Frame from lesson 2

After trimming columns: the posts query selects only id, title, slug, published_at and author_id, and the author eager load selects only id and name. Memory is down to 4.34 MB.

Key takeaway

Fetch only what you show. It matters most on lists, exports and anything touching many rows.

Check yourself

You select only id and title, then eager load author. Every author is null. Why?

Reveal answer

✓ Answer

author_id wasn't selected, so Eloquent has nothing to match posts to authors with.