Home > Mobile >  How to bulk update table in Laravel?
How to bulk update table in Laravel?

Time:06-25

I have a database table with the following columns:

columnindex |  type | id
1               1     1
2               2     1
3               3     1

I have a input array:

$arr = [1 => 2, 2 => 5, 3 => 6,...]

As result I need this:

columnindex |  type | id
1               2     1
2               5     1
3               6     1

How to use update bulk in this case?

I tried this but it is not optimized:

$arr = [1 => 2, 2 => 5, 3 => 6];
foreach($arr as $columnindex => $type) {
    SessionPrepared::where("id", 1)->where("columnindex", $columnindex)->update(["type" => $type]);
}

CodePudding user response:

You are looking for the upsert method (https://laravel.com/docs/9.x/eloquent#upserts).

Example:

SessionPrepared::upsert([
    ['id' => 1, 'columnindex' => 1, 'type' => 'value'],
    ['id' => 2, 'columnindex' => 2, 'type' => 'value'],
    ['id' => 3, 'columnindex' => 3, 'type' => 'value'],
], ['id', 'columnindex'], ['type']);

Results in it bulk updating the column type for the provider identifiers id & columnindex

  • Related