Michał Lipa Michał Lipa - 1 year ago 80
PHP Question

Laravel Check if Users have this same relation

I would like to check if two users have these same relation. I have models:


User relations:

public function teams()
return $this->belongsToMany('App\Team');

Team relation:

public function users()
return $this->belongsToMany('App\User');

So users can be part of few teams. How to check if 2 specified users have common team?

Answer Source

What about checking by name in nested loop like so:

$user1 = User::find(1);
$user2 = User::find(2);

foreach($user1->teams->name as $team1)
   foreach($user2->teams->name as $team2)
        if($team1 == $team2)
        //do awesome stuff

The above won't work. The correct code is:

$user1 = User::find(1);
$user2 = User::find(2);

foreach($user1->teams as $team1)
   foreach($user2->teams as $team2)
        if($team1->name == $team2->name)
        //do awesome stuff
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download