Optimise Query using Laravel Cursor
For this scenario, imagine you are querying thousands or millions of "posts" table. Imagine you have 100,000 records, having the code below executed will make the memory full and may even crash the web page.
<?php // when using eloquent $posts = Post::all(); // when using query builder $posts = DB::table('posts')->get(); foreach($posts as $post){ // do something with $post; }
<?php // when using eloquent foreach(Post::cursor() as $post){ // do something with $post; } // when using query builder foreach(DB::table('posts')->cursor() as $post){ // do something with $post; }
Use Collection each Method to Loop
One of the ways to loop the eloquent instance is to use Laravel collection "each()" method and in generate I would have considered this my choice of writing loops.
<?php Post::cursor()->each(function ($post) { // do something with post });
Leave a reply