Vivek Mistry 👋

I’m a Certified Senior Laravel Developer with 8+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 27 Mar, 2026
  • 24 Views
  • Insert or update bulk data in a single query without loops.

Update Multiple Records Efficiently in Laravel Using upsert()

The Problem: Loop-Based Inserts & Updates

In real Laravel applications, handling bulk data often looks like:

foreach ($products as $product) {
    Product::updateOrCreate(
        ['sku' => $product['sku']],
        ['price' => $product['price']]
    );
}

This runs multiple queries → slow and inefficient.


The Better Solution: upsert()

Laravel provides upsert() to handle bulk insert/update in one query.

Product::upsert(
    [
        ['sku' => 'P001', 'price' => 100],
        ['sku' => 'P002', 'price' => 200],
    ],
    ['sku'], // unique column
    ['price'] // columns to update
);

Real Project Example

Imagine syncing products from an external API:

Product::upsert($apiProducts, ['sku'], ['price', 'stock']);

Now:

  • New products → inserted
  • Existing products → updated
  • Only one query executed

Why upsert() Is Powerful

It helps you:

  • Reduce database queries
  • Improve performance
  • Handle bulk data efficiently
  • Simplify sync operations

When to Use It

Use upsert() when:

  • Syncing external data
  • Bulk import/export
  • Updating large datasets
  • Working with APIs or CSV uploads

Share: