Level 41
The most efficient approach to me is to use the enrolments table is the intermediary table for a many to many relationship between environments and users (I believe Enrolment is the correct word).
public class User
{
public function enrolments()
{
return $this->hasMany(Enrolment::class);
}
public function environments()
{
return $this->belongsToMany(Environment::class, 'enrolments');
}
}
public class Environment
{
public function enrolments()
{
return $this->hasMany(Enrolment::class);
}
public function users()
{
return $this->belongsToMany(User::class, 'enrolments');
}
}
public class Enrolment
{
public function user()
{
return $this->belongsTo(User::class);
}
public function environment()
{
return $this->belongsToMany(Environment::class,);
}
}
Then the enrolment of a user in a given environments:
return $user->enrolments()
->where('environment_id', $environment->id)
->first();
// Or
$user->enrolments
->first(fn (Enrolment $enrolment) => $enrolment->environment->is($environment));