Problem
When processing large datasets, accessing relations via Eloquent properties causes memory usage to keep climbing. The reason is that each Model instance caches loaded relations on itself, and after iterating through the loop, all these objects remain in memory.
This issue was reported in a Laracasts discussion thread, where someone also found a solution.
Solution
After using a relation, manually call setRelations([]) to clear the cache:
| |
Some people in the thread also mentioned using $user->setRelation('posts', null) to clear a single relation, but in practice the results were unreliable. I recommend clearing all relations to be safe.
