How to Avoid Duplicate Entry when using updateOrCreate()

Viewed 26

I am using updateOrCreate function for, when branchid, productid, batch_no is same update stock record or when these fields have different values create new stock record. some times duplicate stock record created. How to avoid It.

Stocks::updateOrCreate(
            ['branch_id' => $event->branch_id, 'product_id' => $event->product_id, 'batch_no' => $event->batch_no],
            ['manufacture_date' => $event->manufacture_date, 'expire_date' => $event->expire_date, 'current_stock' => $current_Stock, 'price' => $event->price]
        );
1 Answers

You need to have a unique index on branchid, productid, batch_no in your database.

Then the engine will see that the new entry is a duplicate of an existing one.

Related