Mr.SH
Mr.SH

Reputation: 457

Laravel 8 Eloquent upsert inserting new records

I am trying to understand Laravel 8's new feature upsert.

Here is my sample table:

flights
id (primary key and auto Inc)
departure
destination
price

In my code:

App\Models\Flight::upsert([
    ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
    ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination']);

This is the sample table from Laravel documentation and it has one key id.

I want to update the record if both departure and destination are matched but these fields are not unique.

Every time I run the code, it inserts a new record but does not update. How to get upsert working?

Do I need to make both departure and destination unique or will it work without making them unique?

Also if I need to make both fields unique then how can I do it in migration?

Upvotes: 13

Views: 16961

Answers (3)

bayusamara
bayusamara

Reputation: 421

I had the same problem, i make the second parameter as "composite unique".

Add this to migration

$table->unique(['departure','destination']); 

The problem should gone

Documentation

Starting in Laravel 9.x, the Eloquent documentation page was updated to mention the fact that upsert() depends on DB unique constraint:

All databases except SQL Server require the columns in the second argument of the upsert method to have a "primary" or "unique" index. In addition, the MySQL database driver ignores the second argument of the upsert method and always uses the "primary" and "unique" indexes of the table to detect existing records.

Upvotes: 32

Jesse Long
Jesse Long

Reputation: 9

You need the third parameter for the column to be updated.

Flight::upsert([
    ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
    ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);

Upvotes: 0

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

I believe you need pass the unique key in the second parameter of upsert which is the id column and primary key of the table, the sample data would be

App\Models\Flight::upsert([
    ['id'=> 1, 'departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
    ['id'=> 2, 'departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['id']);

Upvotes: 6

Related Questions