title: Recursive relationship with scope
body: <p>A user has a sponsor:</p>
  
  <pre><code>public function sponsor()
  {
      return $this-&gt;belongsTo(User::class, 'sponsor_id');
  }
  </code></pre>
  
  <p>A user has referrals:</p>
  
  <pre><code>public function referrals()
  {
      return $this-&gt;hasMany(User::class, 'sponsor_id');
  }
  </code></pre>
  
  <p>A user is considered capped when they have 2 or more referrals:</p>
  
  <pre><code>public function activeReferrals()
  {
      return $this-&gt;referrals()-&gt;whereActive(true);
  }
  
  public function isCapped()
  {
      return $this-&gt;activeReferrals()-&gt;count() &gt;= 2;
  }
  </code></pre>
  
  <p>A user can give points. By default, the sponsor will receive them, but if the sponsor is capped, I want the points to go to a sponsor's referral that is NOT capped. If all the referrals are capped, then it does the same thing with the level below (the referral's referrals).</p>
  
  <p>If I go user by user making database calls for each one, it's gonna take a long time. <strong>How can I write a scope that makes recursive calls until it finds the first active referral in the tree that's not capped?</strong></p>
  
  <p>This is what I'm trying to do:
  <img src="https://i.imgur.com/LBPBlvg.png" alt=""></p>