How to use conditions in Eloquent relationships
Categorized as Laravel
You can use conditions in Eloquent with relationships. For example, we’ve got a Team and its Users. We can define the relationship with the name “admins” which extends the user relation with a condition.
class Team extends Model
{
public function users()
{
return $this->hasMany(User::class);
}
public function admins()
{
return $this->users()->where('role', 'admin');
}
}