Update multiple rows at once Laravel Eloquent
Asked Answered
B

2

10

I have the table products with the following structure.

id | name | promote

Where the column promote is of boolean type.

I want to set the value of the boolean column to 1 with the selected rows and set 0 to non-selected rows. I have the following code in the controller to handle this query.

$yes = Tour::whereIn('id', $request->promote)->get();
$no = Tour::whereNotIn('id', $request->promote)->get();

foreach ($yes as $item) {
    $item->promote = 1;
    $item->save();
}

foreach ($no as $item) {
    $item->promote = 0;
    $item->save();
}

I get following from the form request.

enter image description here

The above code does work but it isn't very efficient I assume. I'm looking for optional ways to achieve the result in a more efficient way.

Bore answered 30/12, 2019 at 15:38 Comment(0)
S
10

Instead retrieving result, looping through, you can update directly,

$yes =  Tour::whereIn('id', $request->promote)->update(['promote' => 1]);
$no =  Tour::whereNotIn('id', $request->promote)->update(['promote' => 0]);
Seesaw answered 30/12, 2019 at 15:48 Comment(0)
S
4

If you don't care about going through the Model to do the updating you can call update on the builder to update all the matched records. As this will use the builder and not the Model there will not be any model events fired:

// set them all to promote = 0
Tour::update(['promote' => 0]);
// or  just set the ones that need to be 0
Tour::whereNotIn('id', $request->promote)->update(['promote' => 0]);

// set the ones you want to promote = 1
Tour::whereIn('id', $request->promote)->update(['promote' => 1]);

Just one way to give it a go.

Strongwilled answered 30/12, 2019 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.