TechnicalEloquent performance

Eloquent performanceLesson 4 of 28

Dynamic Relationships Using Subqueries

Subquery the ID, then let belongsTo do the rest.

2 min readIntermediateLesson

Eloquent performance04

The problem

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.

The fix

Use a subquery to fetch only the ID of the last login, then treat that ID as the foreign key for a normal belongsTo.

✕ Instead of this

public function lastLogin()
{
    return $this->hasOne(Login::class)->latest();
}

User::with('lastLogin')->get();
// Still loads all 7,500 logins to keep 15

✓ Do this

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();

The benefit

A full Login model per user (IP, device, any method) with just 15 logins loaded, instead of one subquery per field.

Results

Queries

3. 15 users + 15 logins, nothing extra

Why it works

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.

Watch out

  • It only works when the scope is applied, so you can't lazy-load it. That's fine: you only use it where you're already optimising.
  • Why not 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.

Frame from lesson 4

The dynamic relationship: a normal lastLogin() belongsTo, plus scopeWithLastLogin() which supplies the missing last_login_id via an addSelect subquery and eager loads it.

Key takeaway

Subquery the ID, then let belongsTo do the rest.

Check yourself

Why does $user->lastLogin return null when you forget withLastLogin()?

Reveal answer

✓ Answer

last_login_id isn't a real column. It only exists when the scope adds it to the query.