Bulk Data Insertion: Update Or Insert in One Go with Laravel's Upsert
Nov
17

Bulk Data Insertion: Update Or Insert in One Go with Laravel's Upsert

Discover the efficiency of Laravel's Upsert method, a powerful way for seamlessly handling large database insertions and updates in a single step. By combining the processes of inserting new records and updating existing ones, upsert significantly reduces the number of queries.

Why Use Upsert?

  • Minimizes database queries, enhancing overall application speed.
  • Ideal for scenarios involving large data insertion, ensuring clean and unique records.
  • Streamlines code by handling both insertion and updating in a single method call.

In the following example, we want to either insert new products or update the price if the combination of product name and brand matches an existing record using Laravel's Upsert method. We provide the data for adding or updating in first argument this could be a large amount of data. For the second argument, we'll specify the columns that uniquely identify each record—namely, the product name and brand. Finally, in the third argument, we'll specify the columns that should be updated in case of a matching record.

        $productDataToInsertOrUpdate = [
            [
                'name' => 'Product 1',
                'brand' => 'ABC',
                'price' => 19.99
            ],
            [
                'name' => 'Product 2',
                'brand' => 'DEF',
                'price' => 29.99
            ],
            [
                'name' => 'Product 3',
                'brand' => 'XYZ',
                'price' => 39.99
            ],
            // ..
        ];


        App\Models\Product::upsert(
            $productDataToInsertOrUpdate,
            ['name','brand'],
            ['price']
        );

Ensure that the column used for the upsert operation should have a unique constraint,

Conclusion

Laravel's upsert method is a game-changer for developers looking to optimize database insertions and updates. By minimizing queries, upsert is a valuable addition to your knowldge.

Happy coding!

 

 

 

Contact

Get in touch with us

Feel free to request missing tools or give some feedback.

Contact Us