Created
July 22, 2018 20:16
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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