PHP

Bulk Insert or Update Records with Eloquent Upsert

Learn how to efficiently insert new records or update existing ones in bulk using Laravel Eloquent's `upsert` method for optimized database operations.

use App\Models\Product;
use Illuminate\Support\Facades\DB;

$products = [
    ['name' => 'Laptop', 'price' => 1200.00, 'in_stock' => 10, 'sku' => 'LAP-001'],
    ['name' => 'Mouse', 'price' => 25.00, 'in_stock' => 50, 'sku' => 'MOU-002'],
    ['name' => 'Keyboard', 'price' => 75.00, 'in_stock' => 30, 'sku' => 'KEY-003'],
    ['name' => 'Laptop Pro', 'price' => 1500.00, 'in_stock' => 15, 'sku' => 'LAP-001'], // Update existing SKU
];

Product::upsert(
    $products,
    ['sku'], // Unique by 'sku'
    ['name', 'price', 'in_stock'] // Columns to update on match
);

// Example with DB facade for non-model based upsert
// DB::table('products')->upsert(
//     $products,
//     ['sku'],
//     ['name', 'price', 'in_stock']
// );
How it works: The `upsert` method allows you to insert records that do not exist, or update records that already exist based on a unique constraint. It takes three arguments: the data to insert/update, the columns that form the unique constraint (e.g., 'sku'), and the columns to update if a matching record is found. This is highly efficient for bulk operations, minimizing database round trips.

Need help integrating this into your project?

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

Hire DigitalCodeLabs