Can't recall seeing this before. What laravel version? Did you try composer update. I would also always eager load my records anyways
Feb 20, 2023
2
Level 2
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
Please or to participate in this conversation.