PHP
Efficient Bulk Operations with Eloquent upsert
Learn how to use Laravel Eloquent's `upsert` method for high-performance bulk inserts and updates, handling conflicts and preventing duplicate records efficiently.
use App\Models\Product;
$products = [
['name' => 'Laptop', 'price' => 1200, 'stock' => 50],
['name' => 'Mouse', 'price' => 25, 'stock' => 100],
['name' => 'Keyboard', 'price' => 75, 'stock' => 75],
['name' => 'Laptop', 'price' => 1250, 'stock' => 45], // This will update existing 'Laptop'
];
// Bulk insert or update products
Product::upsert(
$products,
['name'], // Columns that should be unique
['price', 'stock'] // Columns to update if a match is found
);
// You can also add timestamps automatically
$now = now();
$productsWithTimestamps = array_map(function ($product) use ($now) {
$product['created_at'] = $now;
$product['updated_at'] = $now;
return $product;
}, $products);
Product::upsert(
$productsWithTimestamps,
['name'],
['price', 'stock', 'updated_at']
);
How it works: The `upsert` method provides an efficient way to insert records into the database or update them if a matching record already exists. It takes three arguments: an array of arrays representing the records to insert/update, an array of column names that should be unique (used to detect duplicates), and an array of column names to update if a duplicate is found. This is significantly faster than individual `firstOrCreate` or `updateOrCreate` calls for bulk operations.