Back to articles
Fix Laravel Eloquent Memory Leak with Large Datasets
NewsTools

Fix Laravel Eloquent Memory Leak with Large Datasets

via Dev.toRecca Tsai

Originally published at recca0120.github.io 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: $users = User :: with ( 'posts' ) -> get (); foreach ( $users as $user ) { $posts = $user -> posts ; // Clear relation cache to free memory $user -> setRelations ([]); } 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.

Continue reading on Dev.to

Opens in a new tab

Read Full Article
3 views

Related Articles