jaspercreel's avatar

Eager loading a relationship returning empty

Hi all,

Eager loading a many-to-many relationship with a "wherePivot" clause is making it empty, even though there is data. I can do this:

$thing->relations;

and there is data. But if I do this:

$thing->load('relations');

it is empty.

The relationship looks like this:

public function relations()
{
  return $this->belongsToMany(Relation::class)->withPivot('other_id', $this->other_id);
}

What could be causing this? Anyone else encounter this?

1 like
2 replies
LaryAI's avatar
Level 58

The issue appears to be related to how you're using the withPivot method within your relationship definition. Specifically, this part:

withPivot('other_id', $this->other_id)

The withPivot method is used to include additional columns from the pivot table in your relationship, but you're passing in a column value ($this->other_id), not just the column name.

How it should be used:

return $this->belongsToMany(Relation::class)->withPivot('other_id');

That way, $thing->relations will include the other_id column from the pivot table on each related model.

Regarding Filtering (wherePivot)

If you want to only load related models where the pivot column (e.g., other_id) matches a certain value, you should use the wherePivot clause in your relationship call, not in the relationship method itself. For example:

$thing->relations()->wherePivot('other_id', $thing->other_id)->get();

Or, if you're eager loading:

$things = Thing::with(['relations' => function($q) use ($someOtherId) {
    $q->wherePivot('other_id', $someOtherId);
}])->get();

Summary

  • Change your relationship to:

    public function relations()
    {
        return $this->belongsToMany(Relation::class)->withPivot('other_id');
    }
    
  • Use wherePivot at the time you query or eager load, not in the relationship definition itself.

Full Example:

$thing = Thing::with(['relations' => function ($q) use ($thing) {
    $q->wherePivot('other_id', $thing->other_id);
}])->find($thing->id);

Reference:

Let me know if you need more help!

Snapey's avatar

a common problem with relationships is having a column with the same name

1 like

Please or to participate in this conversation.