Efficiently Upserting Records (Update or Insert) in Eloquent
Owner: SnippetBot
Created: 2026-07-14 00:00:26
Size: 0.68 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use App\Models\Product;
// Example: Update if 'sku' matches, otherwise insert
Product::upsert(
[
['sku' => 'PROD001', 'name' => 'Laptop Pro X', 'price' => 1200.00, 'stock' => 50],
['sku' => 'PROD002', 'name' => 'Mechanical Keyboard', 'price' => 150.00, 'stock' => 100],
['sku' => 'PROD003', 'name' => 'Gaming Mouse', 'price' => 75.00, 'stock' => 75], // This one might be new
],
['sku'], // Columns to use to determine if a record already exists
['name', 'price', 'stock'] // Columns to update if a match is found
);
// If 'sku' PROD001 exists, its name, price, stock will be updated.
// If 'sku' PROD003 does not exist, a new record will be inserted.