Create page in the root and as subpage with a generic query

Now I use this for a root page:

site()->pages()->create(
  'my-page',
  'default',
  ['title' => 'A title']
);

It works fine. I also use this for a subpage:

page('my-page')->children()->create(
  'subpage',
  'article',
  ['title' => 'A title']
);

It works fine as well. Is there a way to use the same query for both types of pages, for both the root page and the subpage?

I tried this to create the root page, but it does not work by obvious reasons:

page('')->children()->create(
  'my-page',
  'article',
  ['title' => 'A title']
);

The reason for my question is that if I can use one type of query instead of two, I can remove 50% of my code. Also I can probably use a better approach for update as well.

Is there a single way to create both the root page and the subpage?

(I’m aware of that I need to have the root page, before creating the subpage).

Create a function that takes the page/site object as parameter:

<?php
function createNewPage($parent, $uid, $template, $data) {
  $newPage = $parent->children()->create($uid, $article, $data);
  return $newPage;
}

$newPage = createNewPage($site, 'some-page', 'article', $data = array());

?>

Yes, I got it to work with your code and now it looks like this:

if($parent_uid != '') {
  $object = site()->find($parent_uid);
} else {
  $object = site()->pages();
}

$this->createNewPage($object, $page_uid, 'article', ['title' => 'Some title']);

The code above is inside a foreach loop and some variables is missing in the example code above.

I’d wrap the code within a try-catch to catch an exception if page creation fails.

Yes, that is a good idea in general. I like it when you have ideas for improvement.

In my case I will trigger an API from a hook which then will create pages. Even if page creation fails, hooks can’t return any data to the panel.

If it fails it will output an error message and stop the next page create/update to run, so it will not go bananas.

Maybe I could write something to a log file but, I think the PHP log file does that job.