Last active
March 22, 2023 12:41
-
-
Save loekwetzels/b384325a0222b7a6394d6c8ea02c6bc0 to your computer and use it in GitHub Desktop.
How to update large data in Laravel
This file contains hidden or 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 | |
// 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