Skip to content
Advertisement

Laravel check if belongstomany contains belongstomany

in my system:

  • a lead belongstomany salespeople
  • a manager belongstomany salespeople

i am trying to check if a lead has a manager through the salespeople. this is for a policy so i can make sure a manager can see the leads of their salespeople.

something like this:

$lead->salespeople->contains($manager->salespeople)

is there a collection method that will allow me to do this? i’ve also tried stuff like this which isn’t working either:

$lead->salespeople->contains('id', $manager->salespeople->pluck('id')->toArray())

edit, i think i got it. does this look correct?:

$lead->salespeople->intersect($manager->salespeople)->count() > 0

Advertisement

Answer

Ended up solving this problem with this package: https://github.com/staudenmeir/eloquent-has-many-deep

Here’s my relationship method now:

public function managers()
{
    return $this->hasManyDeepFromRelations($this->salespeople(), (new User)->setAlias('salesperson')->managers());
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement