PHP
Performing Efficient Batch Updates with Eloquent Query Builder
Optimize database operations in Laravel by performing efficient batch updates on multiple records without loading them into memory, significantly improving performance.
use App\Models\Product;
// Update all products with 'status' of 'pending' to 'approved' and set 'approved_at'
$updatedCount = Product::where('status', 'pending')
->update([
'status' => 'approved',
'approved_at' => now(),
'updated_at' => now() // Eloquent's automatic timestamp update won't trigger
]);
// Batch update for all users in a specific department
$usersUpdated = App\Models\User::where('department_id', 5)
->update(['is_active' => false]);
How it works: This snippet demonstrates how to perform efficient batch updates on multiple records using Laravel Eloquent's query builder. When you call the `update()` method directly on a query builder instance (e.g., after `where()` clauses), Eloquent generates a single SQL `UPDATE` statement, which is executed directly against the database without hydrating any models into memory. This approach is significantly more performant than retrieving each model and updating it individually, especially when dealing with a large number of records.