PHP

Perform Bulk Insert or Update with Eloquent `upsert`

Learn to use Laravel Eloquent's `upsert` method for high-performance batch operations, inserting new records or updating existing ones based on a unique key.

use App\Models\Product;

$productsToUpsert = [
    [
        'name' => 'Laptop Pro',
        'sku' => 'LAPTOP-001',
        'price' => 1200.00,
        'stock' => 50,
    ],
    [
        'name' => 'Mechanical Keyboard',
        'sku' => 'KB-MECH-005',
        'price' => 120.00,
        'stock' => 150,
    ],
    [
        'name' => 'Laptop Pro Max', // New name for existing SKU
        'sku' => 'LAPTOP-001',
        'price' => 1350.00,
        'stock' => 45,
    ],
];

// Assume 'sku' is unique in the 'products' table
Product::upsert(
    $productsToUpsert,
    ['sku'], // Unique by 'sku'
    ['name', 'price', 'stock'] // Columns to update if 'sku' matches
);

echo "Products upserted successfully!
";

// Verify a product
$laptop = Product::where('sku', 'LAPTOP-001')->first();
echo "Laptop Pro SKU: {$laptop->sku}, Name: {$laptop->name}, Price: {$laptop->price}, Stock: {$laptop->stock}
";
How it works: The `upsert` method provides a powerful and highly efficient way to insert records that do not exist or update records that do exist based on a given unique key. This is particularly useful for bulk operations like synchronizing data from an external API or updating large datasets. It takes three arguments: the records to insert/update, the columns that uniquely identify records (used for matching), and the columns that should be updated if a match is found.

Need help integrating this into your project?

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

Hire DigitalCodeLabs