psudo
psudo

Reputation: 1558

Update multiple rows at once Laravel Eloquent

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.

Upvotes: 10

Views: 11867

Answers (2)

lagbox
lagbox

Reputation: 50481

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.

Upvotes: 4

arun
arun

Reputation: 4815

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

Upvotes: 10

Related Questions