Skip to content

Instantly share code, notes, and snippets.

@spaceemotion
Created July 22, 2018 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spaceemotion/fba5f154d39f3cf9483e920868fe744c to your computer and use it in GitHub Desktop.
Save spaceemotion/fba5f154d39f3cf9483e920868fe744c to your computer and use it in GitHub Desktop.
Adds a "chunkSimple" method to Laravel's query builder, so where(Has) clauses don't break with pagination. This might happen if you update the same model in the chunk callback, thus skipping rows. Simply swap out chunk with chunkSimple and hey, presto!
<?php
namespace App\Providers;
use Illuminate\Database\Eloquent\Builder;
class DatabaseServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Chunking that does not break with where clauses
Builder::macro('chunkSimple', function (int $size, callable $callable) {
$page = 1;
while (($chunk = $this->limit($size)->get())->count() >= $size) {
if ($callable($chunk, $page++) === false) {
return false;
}
}
return true;
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment