Laravel 5: Lazy Eager Loading without repeating queries
<p>In my project I'm writing a method on one of my models that uses one of it's relationships and a sub-relationship so I am having to use lazy eager loading:</p>

<pre><code>class MyModel extends Model
{
    public function doSomething()
    {
        // Lazy eager load relationship and subrelationship
        $this-&gt;load('relationship', 'relationship.subrelationship');

        $relatedItems = $this-&gt;relationship;
        foreach ($relatedItems as $relatedItem) {
            $subrelatedItems = $relatedItem-&gt;subrelationship;
            foreach ($subrelatedItems as $subrelatedItem) {
                // Do something...
                return true;
            }
        }

        return false;
    }
}
</code></pre>

<p>The <code>Model::load()</code> method in Laravel can be used to re-load a relationship and does a new database query every time. Therefore, each time I call my method <code>MyModel::doSomething()</code>, (Or call another method that uses similar relationships) another database query is executed.</p>

<p>I know that in Laravel you can call a relationship a number of times like this:</p>

<pre><code>$relatedItems = $model-&gt;relationship;
$relatedItems = $model-&gt;relationship;
$relatedItems = $model-&gt;relationship;
$relatedItems = $model-&gt;relationship;
</code></pre>

<p>..and it doesn't repeat the query since it has already loaded the relationship.</p>

<p>I was wondering if it was possible to avoid querying the database every time I want to use my relationship inside the model? I had the idea that I could use <code>$this-&gt;getRelations()</code> to work out which relationships had been loaded and then just skip them if they already had:</p>

<pre><code>$toLoad = ['relationship', 'relationship.subrelationship'];
$relations = $this-&gt;getRelations();
foreach ($toLoad as $relationship) {
    if (array_key_exists($relationship, $relations)) {
        unset($toLoad[$relationship]);
    }
}

if (count($toLoad) &gt; 0) {
    $this-&gt;load($toLoad);
}
</code></pre>

<p>That works to an extent, it's able to skip loading <code>relationship</code> each time, but <code>relationship.subrelationship</code> isn't actually stored in the array returned by <code>$this-&gt;getRelations()</code>. I would imagine it is stored in the sub-model(s) as <code>subrelationship</code>.</p>

<p>Cheers</p>