Safely Change Status of Subpages

How to safely change status of set of subpages?
Currently iterating with a foreach loop through a set of subpages and changing status misses items as the total changes.

What do you mean exactly?

And could you please post your code?

This is a test case representative of what I am working on

$kirby->impersonate('kirby'); 

$testPage = Page::factory([
  'slug' 	 => 'virtual',
  'template' => 'virtual',
]);

for($i = 0; $i < 10; $i++) {
  $testPage->createChild([
    'slug'    => 'child ' . $i,
    'status'  => 'draft', 
  ]);
}

foreach($testPage->drafts() as $draft) {
  try {
    $unlisted = $draft->changeStatus('unlisted'); 
    // do something with unlisted... 
  }
  catch(Exception $e) {
    dump($e); 
  }
}

and log result

foreach($testPage->childrenAndDrafts() as $child) {
  dump($child->slug() . ' ' . $child->status()); 
}

child-0 unlisted
child-2 unlisted
child-4 unlisted
child-6 unlisted
child-8 unlisted
child-1 draft
child-3 draft
child-5 draft
child-7 draft
child-9 draft

Which Kirby version are you using? I can’t reproduce this.

Hm…

Using 3.3.3

I copied your code into a template in a 3.3.3 Starterkit.

Where are you using this code? Any other custom code?

I deleted kirby and reinstalled - that fixed it. I’m not sure how but the installation have gotten corrupted. Thank you for the help.