title: Laravel Eloquent - Do something before returning models from a relationship
body: <p>We have some circular dependencies between a couple of models and we would like to optimize that.</p>
  <p>Here is a quick overview of the DB schema</p>
  <pre><code>Person : id, main_address_id
  Address: id, addressable_type, addressable_id
  </code></pre>
  <p>Which translates into Eloquent models:</p>
  <pre><code>class Person {
    function addresses() {
        return $this-&gt;morphMany(Address::class, 'addressable', 'addressable_type', 'addressable_id');     
    }
  
    function main_address() {
        return $this-&gt;belongsTo(Address::class, 'main_address_id');     
    }
  }
  
  class Address {
    public function addressable(): MorphTo
    {
        return $this-&gt;morphTo('addressable', 'addressable_type', 'addressable_id');
    }
  
    public function isMainAddress(): bool {
        return $this-&gt;id === $this-&gt;addressable?-&gt;main_address_id;
    }
  }
  </code></pre>
  <p>Everything is working pretty good but we noticed we could save quite a lot of DB queries when dealing with the following type of code:</p>
  <pre><code>$addresses = $person-&gt;addresses;
  
  foreach ($addresses as $address) {
      $address-&gt;isMainAddress(); // Loads the addressable from DB to check the IDs
  }
  </code></pre>
  <p>One easy fix on the above code is to add a call to setRelation:</p>
  <pre><code>$addresses = $person-&gt;addresses-&gt;each(fn($a) =&gt; $a-&gt;setRelation('addressable', $person));
  </code></pre>
  <p>That way, the addressable relationship from each address is not queried.</p>
  <p>All is fine in a simple case like that, we want to avoid manually doing the setRelation in each place we need it.</p>
  <p>Basically we are looking for a way to run a callback on the models returned by the relationship after each time it gets queries. Something like that basically:</p>
  <pre><code>  function addresses() {
        return $this-&gt;morphMany(Address::class, 'addressable', 'addressable_type', 'addressable_id')
            -&gt;prepareModels(fn($a) =&gt; $a-&gt;setRelation('addressable', $this));     
    }
  
    function main_address() {
        return $this-&gt;belongsTo(Address::class, 'main_address_id')
            -&gt;prepareModels(fn($a) =&gt; $a-&gt;setRelation('addressable', $this));     
    }
  </code></pre>
  <hr />
  <p><strong>Kindly note that this is a pure Laravel question. I am not looking for advice regarding how the DB schema would be better another way.</strong></p>