Update Multiple Records Efficiently in Laravel Using upsert()
The Problem: Loop-Based Inserts & Updates
In real Laravel applications, handling bulk data often looks like:
foreach ($products as $product) {
Product::updateOrCreate(
['sku' => $product['sku']],
['price' => $product['price']]
);
}
This runs multiple queries → slow and inefficient.
The Better Solution: upsert()
Laravel provides upsert() to handle bulk insert/update in one query.
Product::upsert(
[
['sku' => 'P001', 'price' => 100],
['sku' => 'P002', 'price' => 200],
],
['sku'], // unique column
['price'] // columns to update
);
Real Project Example
Imagine syncing products from an external API:
Product::upsert($apiProducts, ['sku'], ['price', 'stock']);
Now:
- New products → inserted
- Existing products → updated
- Only one query executed
Why upsert() Is Powerful
It helps you:
- Reduce database queries
- Improve performance
- Handle bulk data efficiently
- Simplify sync operations
When to Use It
Use upsert() when:
- Syncing external data
- Bulk import/export
- Updating large datasets
- Working with APIs or CSV uploads