Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fcaivano's avatar

Merge two relationships returns 'Method addEagerConstraints does not exist'

Im getting this error:

BadMethodCallException in Macroable.php line 81: Method addEagerConstraints does not exist.

In my User model im tryng to merge two relationships.

I have the same thing working on a different project but i can't figure out why here it isn't working.

public function stories()
{
return $this->hasMany('App\Models\Story')->where('published','=','1')->orderBy('order');
}

public function photos()
{
return $this->hasMany('App\Models\Photo')->where('published','=','1')->orderBy('order');
}

public function content()
{
return $this->stories->union($this->photos);
}

Version: Laravel 5.2.*

Does anyone had the same error o has any clue why it happens... i've been debugging for a while without any clues

Thanks in advance :)

0 likes
2 replies
jekinney's avatar

Either what @mdecooman or

$this->load('stories', 'photos'); Lazy eager loading

Or

return collect($this->stories, $this->photos);

Separate collection of just stories and photos.

The issue your having is Union is part of the query builder and as doesn't exist in eloquent.

https://laravel.com/docs/5.2/queries#unions

That's why it's docs are under query builder. The eloquent relationship already established the union/join. So obviously it will be confused and through an error.

Yes, eloquent and query builder use same method names but in most cases the code inside the method is different.

https://laravel.com/api/5.2/

Search a method and see the namespaces. Eloquent or Query will give you a hint.

https://laravel.com/api/5.2/search.html?search=Union

As you see no eloquent namespace. Hence your issue.

Please or to participate in this conversation.