Skip to content

Instantly share code, notes, and snippets.

@loekwetzels
Last active March 22, 2023 12:41
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 loekwetzels/b384325a0222b7a6394d6c8ea02c6bc0 to your computer and use it in GitHub Desktop.
Save loekwetzels/b384325a0222b7a6394d6c8ea02c6bc0 to your computer and use it in GitHub Desktop.
How to update large data in Laravel
<?php
// source: https://42coders.com/how-to-update-large-data-in-laravel
$query = App\Models\User::where('active', true);
$count = $query->count();
/** @var \Symfony\Component\Console\Helper\ProgressBar */
$this->bar = $this->output->createProgressBar($count);
$this->bar->start();
$query
->chunkById(200, function ($users){
try {
DB::beginTransaction();
foreach($users as $user){
$user->active = false;
$user->save();
$this->bar->advance();
}
DB::commit();
} catch (\Exception $e) {
//handle your error (log ...)
DB::rollBack();
$this->bar->finish();
}
});
$this->bar->finish();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment