How to use conditions in Eloquent relationships

Categorized as Laravel Tagged

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');
  }

}

Leave a reply

Your email address will not be published. Required fields are marked *