Baldor's avatar

belongsToMany returns every record

Simple belongsToMany relationship.

public function abc(): BelongsToMany
{
	return $this->belongsToMany(Abc::class, 'pivot_table');
}

$model = Model::find($id)->abc lists all records in pivot_table. Regardless if they belong to model or not.

$model->load('abc')->abc lists correctly only Abc that belongs to the model.

$model = Model::with('abc')->find($id)->abc correct as well

So whats the deal? Why would belongsToMany return all instead of null when not "loaded"?

There is an old post at SO https://stackoverflow.com/questions/43035200/laravel-eloquent-belongstomany-returning-all-records documenting this behavior

0 likes
2 replies
Sinnbeck's avatar

Can't recall seeing this before. What laravel version? Did you try composer update. I would also always eager load my records anyways

Baldor's avatar

Currently Laravel 9.51.0 No question about eager loading. Problem is getting wrong data.

$model->has('abc') also happily returns true, even if 0 are related.

I suspected 2 packages related to eloquent (caching and eager load limit), but taking those out of picture, did not change a thing. Eager load limit package was not even used for models in question.

Please or to participate in this conversation.