Sort users by their most recent login. A join returns a row per login: 30,000 rows instead of 60.
Join + group by
~42 ms
Eloquent performanceLesson 17 of 28
hasMany: subquery first. It's cleaner and here faster.
1 min readIntermediateLesson
Sort users by their most recent login. A join returns a row per login: 30,000 rows instead of 60.
Use a subquery that gets each user's latest login date.
User::join('logins', 'logins.user_id', '=', 'users.id')
->select('users.*')
->orderByDesc('logins.created_at');
// one row per login: 30,000 rows for 60 users
User::orderByDesc(Login::select('created_at')
->whereColumn('logins.user_id', 'users.id')
->latest()
->take(1)
);
One row per user, no grouping, and the fastest option here (~25 ms).
Join + group by
~42 ms
Subquery
~25 ms
The join version also works, but needs grouping and an aggregate so MySQL knows which of the 500 dates to use:
User::join('logins', 'logins.user_id', '=', 'users.id')
->groupBy('users.id')
->orderByRaw('max(logins.created_at) desc');

The subquery approach for hasMany: order by (select created_at from logins where user_id = users.id order by created_at desc limit 1) desc. Users are ordered by most recent login, with no GROUP BY or duplicate rows to deal with.
hasMany: subquery first. It's cleaner and here faster.
Why does MySQL error when you add groupBy('users.id') but order by logins.created_at?
✓ Answer
Each user now has many dates in one group, and MySQL doesn't know which one to sort by. Use max().