Laravel: How to update all rows in table
Recently I had to update all Laravel Eloquent model objects with the same values at once. While updating each object one by one is a possibility, it's terribly inefficient and not recommended.
This article outlines how you can set every row with the same values using Laravel's Eloquent.
The efficient way (use this)
Product::query()->update([
'stock' => 0,
'status' => 'private',
]);
The query above results, when prepared, in the following SQL statement:
UPDATE `products` SET `stock` = 0, `status` = 'private'
This is exactly what we want. Just a single statement, your database handles the rest.
The inefficient way (don't use this)
This is inefficient, because it first queries all objects from your database, stores them in memory, assigns the objects to a variable one by one and updates them one by one. When you have a large database, it consumes lots of memory, and costs many database queries.
foreach (Product::all() as $product) {
$product->update([
'stock' => 0,
'status' => 'private',
]);
}
Bonus: adding WHERE clauses
If you also want to add WHERE clauses to filter specific rows, use this:
// Update all products with status 'publish' or status 'unlisted'
Product::whereIn('status', ['publish', 'unlisted'])
->update([
'stock' => 0,
'status' => 'private',
]);