Abdallah Sakre
Abdallah Sakre

Reputation: 915

Not able to update a field using Foreach in Laravel

I have the following array :

var_dump($steps_filt);

Output :

array(2) { [0]=> string(15) "Text1" [1]=> string(23) "Text2" }

And the following object :

var_dump($step_ids);
object(Illuminate\Support\Collection)#400 (1) { ["items":protected]=> array(2) { [0]=> int(2339) [1]=> int(2340) } }

I'm trying to update the $step_ids fields with the $steps_filt values using the below, but I'm sure there is something wrong, since the output is incorrect :

   foreach($step_ids as $index => $steps_filt){

   DB::table('steps')->where('id', $step_ids)->update(['step' => $steps_filt]);

                    }

Upvotes: 0

Views: 1374

Answers (1)

Wesley - Synio
Wesley - Synio

Reputation: 684

Did you check the error log? It might give you an indication of what could be wrong.

But here's a possible problem: The $step_ids variable is a Laravel Collection. You are looping over the items in the collection, but the DB::table('steps')->where() call is referencing the collection instead of the current item ID (which you have named $steps_filt).

I think you might be misunderstanding how a foreach loops works in PHP. At the first iteration of the loop $index will be 0 and $steps_filt will be 2339 for example.

A naive solution to do what you want could be this:

$step_ids_array = $step_ids->toArray(); // Easier to work with if both are array (or collection)
for ($i = 0; $i < count($step_ids_array); ++$i) {
    $step_id = $step_ids_array[$i];
    $step_text = $steps_filt[$i];
    DB::table('steps')->where('id', $step_id)->update(['step' => $step_text]);
}                 

Update: Perhaps a bit cleaner to solve it like this:

$combined = $step_ids->combine($steps_filt);

// $combined will now be a collection where the keys are the IDs and the values are the texts

foreach ($combined as $step_id => $step_text) {
    DB::table('steps')->where('id', $step_id)->update(['step' => $step_text]);
}

Upvotes: 1

Related Questions