PHP
Perform Batch Updates on Eloquent Models
Learn to perform efficient batch updates on multiple Eloquent records using the query builder's `update()` method, avoiding individual model hydration for better performance.
use App\Models\Product;
// Update all inactive products to active and set an updated timestamp
$affectedRows = Product::where('status', 'inactive')
->update([
'status' => 'active',
'updated_at' => now(), // Automatically handled by Eloquent timestamps, but can be explicit
]);
echo "Updated $affectedRows products.
";
// Batch update based on a condition involving a relationship
// Note: This requires a JOIN or subquery for related conditions,
// or filtering based on an already existing column from the main table.
// For direct relation conditions, `whereHas` is typically used (but excluded per instructions).
// Here's a simpler example for clarity, assuming a 'category_id' column:
$affectedRowsCategory = Product::where('category_id', 5)
->where('price', '>', 100)
->update(['discounted' => true]);
echo "Updated $affectedRowsCategory products in category 5.
";
How it works: This snippet demonstrates how to perform efficient batch updates on Eloquent models without retrieving and hydrating each model individually. By calling the `update()` method directly on a query builder instance, Laravel executes a single SQL update statement, significantly improving performance for bulk operations. The examples show updating records based on single and multiple conditions.