Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ligonsker's avatar

Using upsert in Laravel 6

If I need the upsert function but I'm using Laravel 6. Is my only option to use a foreach loop and individually insert the rows using something like updateOrCreate ?

Because I get an array from the request:

['id_x' => 'data', 'id_y' => 'data']

And I need to either insert each value to a new row, or update the row if the id exists

0 likes
4 replies
jlrdw's avatar

For updateOrCreate I suggest work the example from documentation to get a better understanding of how it works.

Also look it up in the API to further study it's inner workings:

https://laravel.com/api/6.x/

1 like
Ligonsker's avatar

@jlrdw I currently work with updateOrCreate because I do it in a foreach loop. My example above was not sufficient, in reality I have an array of arrays that needs to be created or updated where 2 columns have specific values:

foreach ($data_arr as $data_to_insert) {
    $update_or_create = Model::updateOrCreate(
        ['id' => $id, 'column' => $column],
        $data_to_insert
    );
}

But I wonder if it would be possibe to insert the $data_arr at once without a loop

jlrdw's avatar

@Ligonsker why would you need a foreah:

In the example, there is only one

['departure' => 'Oakland', 'destination' => 'San Diego']

That's the whole idea of the method, to insert one if not exist.

So if you use a foreach in each loop as long as the condition differs. But it sounds like you should check out using a database transaction.

And I admit it's not totally clear what you are trying to do.

1 like
Ligonsker's avatar

@jlrdw Sorry I may have written a confusing topic and mixed a few things you're correct now that I look at it 😅.

I will try to make it more organized:

I have an array of arrays of data:

$data_arr = [
['id' =>'x', 'condition'=>'xx', 'col1' => 'col1_value', 'col2' => 'col2_value'],
['id' =>'y', 'condition'=>'yy',  'col1' => 'col1_value', 'col2' => 'col2_value'],
['id' =>'z', 'condition'=>'zz', 'col1' => 'col1_value', 'col2' => 'col2_value'],
// and so on
]

And I want to either create or update the table where the id and condition match together, for all the rows at once.

But right now what I do is foreach on the $data_arr, and I also filter out id and condition into the variables $id and $condition beforehand so it matches the createOrUpdate syntax:

foreach ($data_arr as $data) {
    $update_or_create = Model::updateOrCreate(
        ['id' => $id, 'condition' => $condition],
        $data
    );
}

Please or to participate in this conversation.