PHP
Efficiently Upserting Records in Laravel Eloquent
Learn how to use Laravel Eloquent's `upsert` method to efficiently insert new records or update existing ones based on unique constraints, simplifying your data operations.
use App\Models\Product;
// Single record upsert
Product::upsert(
[
['name' => 'Laptop Pro X', 'sku' => 'LPX-001', 'price' => 1200.00, 'stock' => 50],
],
['sku'], // Unique columns to check for existing records
['name', 'price', 'stock'] // Columns to update if record exists
);
// Multiple records upsert
Product::upsert(
[
['name' => 'Monitor Ultra HD', 'sku' => 'MUHD-002', 'price' => 450.00, 'stock' => 100],
['name' => 'Wireless Keyboard', 'sku' => 'WK-003', 'price' => 75.00, 'stock' => 200]
],
['sku'],
['name', 'price', 'stock']
);
How it works: The `upsert` method allows you to insert records that don't exist or update records that already exist based on a given set of unique columns. The first argument is an array of data, the second is the unique column(s) that identify a record, and the third is the column(s) to update if a matching record is found. This is highly efficient for bulk operations and avoids race conditions often associated with separate `firstOrCreate` or `updateOrCreate` calls.