0

I have an array of objects in my Laravel controller. I need to loop over each object in the array and set the 'status' of each object to 0. I have the following in my controller:

            if (request('status')=='Reset') {
            $allDemoTasks = DemoTask::all();

            foreach($allDemoTasks as $index=>$key) 
               $key->status=0;
               $key->save();
            }

It appears to be setting the last object in my array to 0 and not doing anything to the other objects.

2 Answers 2

3

Your approach will make count($allDemoTasks) separate updates to your database. It is much better to do it in a single statement like:

DB::table('demo_tasks')->update(['status' => 0]);

or

DemoTask::query()->update(['status' => 0]);
Sign up to request clarification or add additional context in comments.

2 Comments

Or even DemoTask::query()->update(['status' => 0]);.
@Tpojka For sure, I will add it!
0

Here is a way using eloquent

if(request('status') == "Reset"){
        App\DemoTask::all()
      ->update(['status' => 0]);
}

2 Comments

why would you hit the database again to retrieve the object you already have?
You took the original question, and added an unnecessary query to it.

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.