0

using Laravel's Eloquent, I'm trying to add an incremental counter to certain rows based on their 'product_id'.

I thought I could do it like this :

$foos = GanttTask::where('product_id',1)->orderBy('date', 'ASC');

$counter = 1;

foreach($foos as $foo){
    $foo->custom_counter = $counter;
    $counter +=1;
}

return $foos->get();

But this is of no effect on my data, custom_counter column doesn't change (but I get no error).

I tried to add $foo->save() within my loop with no effect.

2
  • So I tried but with no effect in the database. With this change, return $foos; returns me an array with correct values. Commented Jan 24, 2018 at 2:30
  • Try your code with foreach($foos as &$foo){. Commented Jan 24, 2018 at 13:51

2 Answers 2

1

Get first all record and then modify single record using save method like this:

$foos = GanttTask::where('product_id',1)->orderBy('date', 'ASC')->get(); // Get All records

$counter = 1;
foreach($foos as $foo){
    $foo->custom_counter = $counter;
    $counter +=1;
    $foo->save(); // Update each record
}

Good Luck !!!

Sign up to request clarification or add additional context in comments.

Comments

0

To actually update the database, I reckon you need to persist each data object foo individually not the collection foos as a whole.

$foos = GanttTask::where('product_id',1)->orderBy('date', 'ASC');

$counter = 1;

foreach($foos as $foo){
    $foo->custom_counter = $counter;
    $counter +=1;
    $foo->save(); // Persisting data here
}

1 Comment

Still no effects on my table!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.