Routing for Virtual Profile Pages

I would like to change the routing a bit. I create a separate virtual page for each user. This is accessible under /profile/USERID. However, I would like to make this accessible under /profile/USERNAME/USERID/.

However, if the user changes the user name, the same profile should still be accessed.

Possible urls can be, if the user change his name:
/profil/tim/14KHeYF5
/profil/timhartmann/14KHeYF5

There should be no difference, because the same page is called up on the basis of the ID without throwing an error.

Do you have an idea how to solve this? I am at a loss after many attempts.

models/profile.php

<?php

class ProfilePage extends Page
{
  public function children()
  {
    $usersPages = [];
    $users      = kirby()->users();
    $currentUser = kirby()->auth()->currentUserFromSession();
    $isCurrentUser;
    foreach ($users as $key => $user) {
      
      if($currentUser == $user->id()) {
        $isCurrentUser = true;
      } else {
        $isCurrentUser = false;
      }
      $userPages[] = [
        'slug'     => Str::slug($user->id()), // or username if unique
        'num'      => $user->indexOf($users),
        'template' => 'profile',
        'model'    => 'profile',
        'content'  => [
          'title'    => $user->username(),
          'user' => $user,
          'currentUser' => $currentUser,
          'isCurrentUser' => $isCurrentUser,
          'position' => $user->position(),
          'bio' => $user->bio()
        ]
      ];
    }
    return Pages::factory($userPages, $this);

  }
}

If you want the pages to be accessible under a different URL you need to create a route that listens to the new pattern and a model for the single user page with a redefined URL method.

On a side note, you can also get the currently logged-in user with kirby()->user()

I am very grateful that you always try to help. Unfortunately, the proposal doesn’t make it very clear to me what to do. After all, I already have a model that creates pages. I suspect that I have to do something with the routing in the config.

You model is a model for the parent and creates the virtual subpages, yes. So these virtual subpages are accessible via their standard route yourdomain.com/profile/userid.

If you want to change this route, you need a route (in your config, a plugin).

An as already mentioned above, you will want to override the url method in the method for the profile pages (unfortunately, you use are using the same model for the children (profile) as for the parent, which doesn’t make sense.

The children method belong in the parent page (profile), then you need a second template/model/blueprint for the children.