Change parent / subpage dynamically


I’m wondering if there is a way to change the parent of a current page with a given method. I saw in the doc the possibility to copy the page to a new parent via $page->copy(). But ideally the method would directly move the page to a given parent.

The reason I want to be able to do that via the Panel (likely with Janitor Plugin) is that I have a Directory with a list of Students that are separated via subpages, like that:

  • Directory
    — Student A
    — Student B
    — Student C
    — Student D
    — Student E
    — Student F
    — Student G
    — Student H
    — Student I

There is some case where student changes year, so that’s why I would like to be able to change the parent directly. Also each student has an AutoID attributed for relationship purpose – which show in the frontend projects they participated in, so I can’t really delete and create it again because I might lose the relationship with the projects.

I hope that make sense what I’m trying to achieve. There are about 8 years and more to come in the future, so that’s why I decided to split it by year.

There is no method to move a page, but you can use the toolkit’s Dir::move() to move the page folder.

Thank you for your answer. Seeing how the Dir::move() works looks like I could do that:

Dir::move($page->url(), $page->parent()->siblings()->find('2019')->url());

But it seems not working since it’s only to move a directory and not a page, so Dir::move() wouldn’t be really helpful for this case?

Dir::move() needs a file path, not a url

Ah yes good point, so more like that:

$current_page_path = Url::path($page->url());
$target_page_path = Url::path($page->parent()->siblings()->find('2019')->url());


Dir::move($current_page_path, $target_page_path);

But seems not to move the page to the targeted one?

No, you need the absolute file path in the file system, the URL is not helpful here. $page->root()

Thanks for you precious help. I managed to make it work!

   $current_page_path = $page->root();
   $target_page_path = $page->parent()->siblings()->find('2019')->root() . '/' . $page->num() . '_' . $page->slug();


Dir::move($current_page_path, $target_page_path);

Again thank you! Now I just have to figure out how to not messed up the relationship :slight_smile: