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
wherePivotat 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!