How can I rearrange a menu link programmatically? I created Menu Link Content entities and saved them in a menu.

$menu_link = MenuLinkContent::create([
  'title' =&gt; 'Menu item',
  'bundle' =&gt; 'menu_link_content',
  'link' =&gt; [['uri' =&gt; 'internal:/']],
  'menu_name' =&gt; 'testing',
])-&gt;save();

$menu_link_2 = MenuLinkContent::create([
  'title' =&gt; 'Menu item',
  'bundle' =&gt; 'menu_link_content',
  'link' =&gt; [['uri' =&gt; 'internal:/']],
  'menu_name' =&gt; 'testing',
])-&gt;save();


How can I rearrange $menu_link_2 to be a child of $menu_link?

Looking at menu_ui, they seem to update Menu Link Content in a given order, and then rebuild the menu tree; finally, the Menu entity is saved.

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_link_manager-&gt;updateDefinition($menu_link_2-&gt;getPluginId(), [
  'parent' =&gt; $menu_link-&gt;getPluginId(),
]);


How can I rebuild the menu tree and save the menu?

Why? I'm writing a Kernel test for a module that fires when the menu link content has been saved AND then when the Menu itself has been saved.
You can rearrange a custom menu link when you set the 'weight' of the menu. See below code.


$menu_link = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();

$menu_link_2 = MenuLinkContent::create([
  'title' => 'Menu item',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'internal:/']],
  'menu_name' => 'testing',
  'weight' => 0,
])->save();