Adding one subquery per field (date, IP address, ID...) gets messy. You really want the whole Login model, so you can call its methods and relations.
Queries
3. 15 users + 15 logins, nothing extra
Eloquent performanceLesson 4 of 28
Subquery the ID, then let belongsTo do the rest.
2 min readIntermediateLesson
Adding one subquery per field (date, IP address, ID...) gets messy. You really want the whole Login model, so you can call its methods and relations.
Use a subquery to fetch only the ID of the last login, then treat that ID as the foreign key for a normal belongsTo.
public function lastLogin()
{
return $this->hasOne(Login::class)->latest();
}
User::with('lastLogin')->get();
// Still loads all 7,500 logins to keep 15
public function lastLogin()
{
return $this->belongsTo(Login::class);
}
public function scopeWithLastLogin($query)
{
$query->addSelect(['last_login_id' => Login::select('id')
->whereColumn('user_id', 'users.id')
->latest()
->take(1),
])->with('lastLogin');
}
User::withLastLogin()->get();
A full Login model per user (IP, device, any method) with just 15 logins loaded, instead of one subquery per field.
Queries
3. 15 users + 15 logins, nothing extra
A belongsTo only needs a foreign key column. Eloquent can't tell that last_login_id was made up by a subquery rather than stored in the table, so the relationship just works.
hasOne + latest()? Eager loading it still loads all 7,500 logins. Adding limit(1) returns one login across all users, so everyone else gets null.
The dynamic relationship: a normal lastLogin() belongsTo, plus scopeWithLastLogin() which supplies the missing last_login_id via an addSelect subquery and eager loads it.
Subquery the ID, then let belongsTo do the rest.
Why does $user->lastLogin return null when you forget withLastLogin()?
✓ Answer
last_login_id isn't a real column. It only exists when the scope adds it to the query.