Dynamic Menu Items
Sometimes there may be a need to amend the menu at runtime. This can be done with MenuBuilder.
First, publish the MenuBuilder class:
scripts/artisan.sh vendor:publish --tag=nexus-menus-builder
And bind it in NexusServiceProvider:
$this->app->bind(
\Alberon\NexusMenus\Support\MenuBuilder::class,
\App\NexusMenus\Support\MenuBuilder::class,
);
Then edit the Alberon\NexusMenus\Support\MenuBuilder class and fill in the modify() method. Use $this->getItemByCode($code) to retrieve a MenuBuilderItem, then chain any of the methods listed below to modify them.
public function modify(): void
{
// Only apply to a single menu:
if ($this->menu->code === 'top-menu') {
// Retrieve a menu item
$item = $this->getItemByCode('about');
// Change the title / URL:
$item->updateTitle('New Title');
$item->updateUrl('https://www.example.com/');
// Insert additional items as siblings:
$item->insertSeparatorAfter();
$item->insertHeadingAfter('Heading Title');
$item->insertLinkAfter('Link Title', 'https://www.example.com/');
// Insert additional items as children:
$item->insertSeparatorUnder();
$item->insertHeadingUnder('Heading Title');
$item->insertLinkUnder('Link Title', 'https://www.example.com/');
// Change the active (highlighted) item:
$item->setActive();
// Remove the item and all children
$item->remove();
}
}
Most of these methods return the new item (if applicable), or $this so they can be chained together.