Laravel 8 Eloquent upsert inserting new records

Viewed 6342

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?

3 Answers

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

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']);

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']);
Related