Michał Lipa Michał Lipa - 6 months ago 6
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?


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