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.
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.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With