title: Laravel and running through a batch of results
body: <p>I'm having a big head ache with Laravel's <code>chunk</code> and <code>each</code> functions for breaking up result sets.</p>
  
  <p>I have a table, that has a column <code>processed</code> with a value of <code>0</code>. If I run the following code, it goes through all 13002 records.</p>
  
  <pre><code>Record::where(['processed' =&gt; 0])-&gt;each(function ($record) { 
      Listing::saveRecord($record);
  }, 500);
  </code></pre>
  
  <p>This code will run through all 13002 records. However, if I add in some code to mark a record as processed, things go horribly pear shaped.</p>
  
  <pre><code>Record::where(['processed' =&gt; 0])-&gt;each(function ($record) { 
      $listing_id = Listing::saveRecord($record);
  
      $record-&gt;listing_id = $listing_id;
      $record-&gt;processed = 1;
      $record-&gt;save();
  }, 500);
  </code></pre>
  
  <p>When this code runs, only 6002 records are processed. </p>
  
  <p>From my understand of things, that on each iteration of of the <code>chunk</code> (<code>each</code> runs through <code>chunk</code>), that it's executing a new statement.</p>
  
  <p>I've come from using Yii2 and I'm mostly happy with the move, except for this hiccup, which has me pulling my hair out. Yii2 has similar functions (<code>each</code> and <code>batch</code>), but they seem to use result sets and pointers, so even if you update the table while you're processing your results, it doesn't effect your result set.</p>
  
  <p>Is there actually a better way to do this in Laravel?</p>