Laravel upsert operations with Query Builder

Eloquent has updateOrCreate() method which allows you to do exactly want you want. But Query Builder doesn't have similar method.

You can build raw query with Query Builder and use INSERT ... ON DUPLICATE KEY UPDATE as upsert solution.


Now (Oct 6, 2020), Laravel(v8.10.0) has native upsert support. https://github.com/laravel/framework/pull/34698

DB::table('users')->upsert([
    ['id' => 1, 'email' => '[email protected]'],
    ['id' => 2, 'email' => '[email protected]'],
], 'email');

Eloquent has the method called updateOrCreate, which can be used like this example:

<?
$flight = Flight::updateOrCreate(
    [
       'code' => '156787', 
       'destination' => 'COL'
    ],
    [
       'code' => '156787', 
       'destination' => 'COL',
       'price' => 99, 
       'discounted' => 1,
    ],
);
  1. Search by code and destination could by your best to identify your rows.
  2. It creates or updates according to the values given in the second array.

The following is the sign of the method.

/**
 * Create or update a record matching the attributes, and fill it with values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return \Illuminate\Database\Eloquent\Model
 */
public function updateOrCreate(array $attributes, array $values = [])