PHP

Upserting Records (Insert or Update) in Eloquent

Efficiently insert new records or update existing ones in Laravel Eloquent using the `upsert` method, ensuring atomic data operations with minimal code.

use App\Models\Product;

// Scenario 1: Basic upsert for a single record
// If a product with 'sku_123' exists, update its name and price. Otherwise, create it.
Product::upsert(
    ['name' => 'Laptop Pro', 'sku' => 'sku_123', 'price' => 1200.00, 'stock' => 50],
    ['sku'], // Unique by 'sku'
    ['name', 'price', 'stock'] // Columns to update if record exists
);

// Scenario 2: Upserting multiple records
// This is ideal for batch imports or syncing data.
$productsToUpsert = [
    ['name' => 'Keyboard Mech', 'sku' => 'kb_456', 'price' => 150.00, 'stock' => 100],
    ['name' => 'Mouse Gaming', 'sku' => 'ms_789', 'price' => 75.00, 'stock' => 75],
    ['name' => 'Laptop Pro Max', 'sku' => 'sku_123', 'price' => 1500.00, 'stock' => 60] // Will update existing sku_123
];

Product::upsert(
    $productsToUpsert,
    ['sku'], // Unique by 'sku'
    ['name', 'price', 'stock'] // Columns to update
);

// The upsert method returns the number of affected rows (inserted or updated).
How it works: The `upsert` method provides a powerful and efficient way to insert records that do not exist, or update records that already do. It takes three arguments: an array of records (or a single record array) to insert/update, an array of columns that uniquely identify the records (e.g., `sku` in a products table), and an array of columns that should be updated if a matching record is found. This method generates a single database query, making it highly performant for batch operations and ensuring data consistency.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs