PHP
Performing Efficient Batch Updates in Laravel Eloquent
Optimize your Laravel applications by learning how to perform efficient batch updates on multiple Eloquent records without individually retrieving each model, reducing database queries.
use App\Models\Product;
// Update all products where 'status' is 'pending' to 'approved'
$affectedRows = Product::where('status', 'pending')
->update(['status' => 'approved', 'updated_at' => now()]);
// Increment a numeric column for specific products
$affectedRows = Product::where('category_id', 5)
->increment('views', 1);
// Decrement a numeric column
$affectedRows = Product::where('category_id', 5)
->decrement('stock', 5);
echo "Number of affected rows: " . $affectedRows;
How it works: This snippet shows how to perform direct batch updates on Eloquent models without first retrieving them into memory. `Product::where(...)->update(...)` directly updates records matching the query. Similarly, `increment()` and `decrement()` methods are used for atomic updates on numeric columns. These operations are highly efficient for large datasets as they translate directly into a single SQL query.