TechnicalEloquent performance

Eloquent performanceLesson 3 of 28

Getting One Record From a Has-Many Relationship

Need one record from a has-many? Use a subquery, not eager loading.

2 min readIntermediateLesson

Eloquent performance03

The problem

Show each user's last login. A user has many logins. Querying per row is an N+1 (17 queries). Eager loading fixes the query count but loads every login: 7,500 models and 13 MB+.

The fix

Ask the database for just that one value, as an extra column on the users query, using a subquery.

✕ Instead of this

// N+1: one extra query per user
$user->logins()->latest()->first()->created_at;

// Or eager load: every login for every user
User::with('logins')->get();
$user->logins->sortByDesc('created_at')->first();

✓ Do this

User::addSelect(['last_login_at' => Login::select('created_at')
    ->whereColumn('user_id', 'users.id')
    ->latest()
    ->take(1)
])

The benefit

Two queries and only the 15 users you show. No Login models are built at all.

Results

Queries

172

88% lower

Models

7,50015

100% lower

Memory

13 MB+~4 MB

69% lower

More detail

Computed columns aren't cast automatically, so cast at query time to get a Carbon date:

->withCasts(['last_login_at' => 'datetime'])

Then move it into a scope like scopeWithLastLoginAt() so controllers stay readable.

Why it works

The subquery runs inside the main query and returns one value per user. A subquery used as a column must return exactly one column and one row, which is why take(1) is there. Yes, the work moves to the database, but databases are very good at this and it's still a single round trip.

Watch out

  • Here eager loading was worse than the N+1. Loading a whole relation to use one row is a trap.
  • Storing last_login_id on users (denormalising) also works, but keeping it in sync gets complicated. Try a subquery first.

Frame from lesson 3

Subquery result: the Last Login column renders and the Models tab shows just 15 User models (no Login models at all), with 2 queries and ~4 MB of memory.

Key takeaway

Need one record from a has-many? Use a subquery, not eager loading.

Check yourself

You get the error "subquery returns more than one row". What did you forget?

Reveal answer

✓ Answer

take(1) (LIMIT 1). Without it the subquery returns every login for that user.