How to update or create elements with upsert method in Laravel

Categorized as Laravel Tagged

If you want to update or create multiple items at the same time, you can use the upsert method:

  ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
  ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
// these attributes will be used to check if the record exists 
['departure', 'destination'],
// and these are the attributes that will be updated

The method’s first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method’s third and final argument is an array of the columns that should be updated if a matching record already exists in the database.

See the full explanation at Laravel official documentation here.

Leave a reply

Your email address will not be published. Required fields are marked *