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+.
Queries
172
88% lower
Eloquent performanceLesson 3 of 28
Need one record from a has-many? Use a subquery, not eager loading.
2 min readIntermediateLesson
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+.
Ask the database for just that one value, as an extra column on the users query, using a subquery.
// 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();
User::addSelect(['last_login_at' => Login::select('created_at')
->whereColumn('user_id', 'users.id')
->latest()
->take(1)
])
Two queries and only the 15 users you show. No Login models are built at all.
Queries
172
88% lower
Models
7,50015
100% lower
Memory
13 MB+~4 MB
69% lower
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.
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.
last_login_id on users (denormalising) also works, but keeping it in sync gets complicated. Try a subquery first.
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.
Need one record from a has-many? Use a subquery, not eager loading.
You get the error "subquery returns more than one row". What did you forget?
✓ Answer
take(1) (LIMIT 1). Without it the subquery returns every login for that user.