Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the specifics for Laravel Query Builder's updateOrInsert function?

This function is not in the Laravel documentation, I have found it in the source code however I am not completely sure how it should be used. For example, if I am working with products, I want to either insert or update a product in the database based on its UPC. If a product with the same UPC exists, update it with the new values. If not, insert the new values as a new product. How should this be done using this function?

Thank you!

like image 578
Matthew Hirt Avatar asked Jan 04 '23 04:01

Matthew Hirt


1 Answers

Insert or update a record matching the attributes, and fill it with values.

updateOrInsert(array $attributes, array $values = []) 

https://laravel.com/api/master/Illuminate/Database/Query/Builder.html#method_updateOrInsert

DB::table('products')->updateOrInsert(
    [
        'upc' => $request->get('upc'),
    ],
    [
        'upc' => $request->get('upc'),
        'name' => $request->get('name'),
        'vendor' => $request->get('vendor'),
        'description' => $request->get('description')
    ]
);
like image 167
Karl Hill Avatar answered Jan 08 '23 00:01

Karl Hill