Programatically update blocks in a layout

Hi all, I’m hoping someone might be able to help me here. I feel like I’m close but the last thing I have to do is actually update my page with an updated layout from my updated blocks. I have been successful updating a blocks field using a similar solution which is why there is that comment part at the bottom. Hopefully its clear what I’m trying to do, let me know if I can explain anything better!

if ( $newPage->layout()->exists() ) {
  if ( $newPage->layout()->toLayouts()->isNotEmpty() ){
    // There is a layout

    $oldLayoutBlocks = $oldPage->layout()->toLayouts()->toBlocks();
    $newLayoutBlocks = $newPage->layout()->toLayouts()->toBlocks();

    if($newLayoutBlocks->isNotEmpty() ){
      // There are blocks in the layout

      $oldMediaBlocks = $oldLayoutBlocks->filter('type', 'media');
      $newMediaBlocks = $newLayoutBlocks->filter('type', 'media');

      if (Custom\App\App::fieldValuesChanged($oldMediaBlocks->toJson(), $newMediaBlocks->toJson()) ){
        foreach ($newMediaBlocks as $newMediaBlock){
          $old = $newMediaBlock->toArray();
            if ( $newMediaBlock->primaryVideoId()->isNotEmpty() ){
              $data = Custom\App\App::getVideoData($newMediaBlock->primaryVideoId()->value(), $newMediaBlock->primaryVideoResolution()->value());

              $old['content']['primaryVideoThumbnailLink'] = $data['thumbnailLink'];
              $old['content']['primaryVideoLink'] =  $data['fileLink'];
            } else {
              $old['content']['primaryVideoThumbnailLink'] = '';
              $old['content']['primaryVideoLink'] = '';
          $new[] = new Kirby\Cms\Block($old);

        $blocks = new Kirby\Cms\Blocks($new ?? []);

        // $newPage->update([
        //     'primaryBlocks' => json_encode($blocks->toArray()),
        // ]);


I don’t think it’s a good idea to first extract the blocks from the layout, because you end up with a collection of blocks that has no reference to the layouts and columns they belonged to.

Here Bastian posted how you can create layouts programmatically:

So I think your best bet would be to actually loop through the layouts and blocks, change what needs to be changed and then to save it all back.

I’m just wondering why all this is even necessary and can’t be done when rendering on the frontend?