Building a sidebar

A sidebar is a class that implements Wikigods\Sidebar\Sidebar. It receives a Menu through dependency injection, fills it in build() and returns it from getMenu():

namespace App\Sidebars;

use Wikigods\Sidebar\Group;
use Wikigods\Sidebar\Item;
use Wikigods\Sidebar\Menu;
use Wikigods\Sidebar\Sidebar;

class AdminSidebar implements Sidebar
{
    public function __construct(protected Menu $menu)
    {
    }

    public function build(): void
    {
        $this->menu->group('Dashboard', function (Group $group) {
            $group->weight(0);
            $group->hideHeading();

            $group->item('Dashboard', function (Item $item) {
                $item->route('admin.dashboard');
                $item->icon('fa fa-dashboard');
            });
        });

        $this->menu->group('Administration', function (Group $group) {
            $group->weight(10);

            $group->item('Users', function (Item $item) {
                $item->weight(1);
                $item->route('admin.users.index');
                $item->icon('fa fa-users');
            });
        });
    }

    public function getMenu(): Menu
    {
        return $this->menu;
    }
}

Register it in config/sidebar.php:

'sidebar' => [
    'class' => App\Sidebars\AdminSidebar::class,
    'view' => 'admin.partials._sidebar',
    'key' => 'sidebar',
],

The sidebar middleware builds the class on each request (or reads it from the cache), and the rendered HTML is passed to the configured view.

Groups

$menu->group($name, $callback) creates a group or returns the existing one with the same name, so several calls add items to the same group.

Method Description
weight(int $weight) Order of the group (ascending).
hideHeading(bool $hide = true) Don't print the group title.
item($name, $callback) Add an item. See Items.
authorize(bool $state) / authorizePermission(string $permission) See Permissions.

Dependencies in closures

Group and item callbacks are resolved through the container, so you can type-hint services after the group or item:

$this->menu->group('Shop', function (Group $group, \App\Services\Shop $shop) {
    // ...
});

Without the configuration

To render a sidebar yourself, leave sidebar.view empty and use the renderer:

use Wikigods\Sidebar\Presentation\SidebarRenderer;

$html = app(SidebarRenderer::class)->render(app(\App\Sidebars\AdminSidebar::class));

See Multiple sidebars for more than one menu.