Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 460
psudo Avatar asked Jan 25 '23 11:01

psudo


1 Answers

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]);
like image 135
arun Avatar answered Jan 29 '23 02:01

arun