felixdorn/laravel-navigation

Create navigation menus for your Laravel application.

1.0.0 2022-09-18 09:45 UTC

README

Create navigation menus for your Laravel application, works out of the box with Inertia.

Features

  • Inertia support
  • Conditionally add sections / items.
  • Easily specify if a route is active
  • Add metadata to items

Tests Formats Version Total Downloads codecov

Installation

Requires PHP 8.0+

You can install the package via composer:

composer require felixdorn/laravel-navigation

Usage

Creating a navigation bar

use Felix\Navigation\Navigation;

Navigation::register('dashboardSidebar', function (Navigation $navigation) {
    
});

Retrieving a navigation bar

use Felix\Navigation\Navigation;

Navigation::dashboardSidebar()->toArray();
// alternatively, to get the raw tree underneath:
Navigation::dashboardSidebar()->tree();

Conditionally rendered items

use Felix\Navigation\Item;

$navigation->addIf($isAdmin, 'Settings', function (Item $item) {
    // ...
});
$navigation->addUnless($isReader, 'Articles', function (Item $item) {
    // ...
});

Section

Add a section

use Felix\Navigation\Item;
use Felix\Navigation\Section;

$navigation->addSection('Name', function (Section $section) {
    $section->add('Child', function (Item $item) {
        // ...
    });
});

Conditionally rendered sections

use Felix\Navigation\Section;

$navigation->addSectionIf($isAdmin, 'Admin', function (Section $section) {
    // ...
});
$navigation->addSectionUnless($isReader, 'Bookmarks', function (Section $section) {
    // ...
});

Items

/** @var \Felix\Navigation\Item $item **/
$item->route('articles.index');

$item->route('tenant.show', ['tenant' => 1]);

$item->url('https://github.com/felixdorn')

$item->route('articles.index')
    ->activeWhenRouteMatches('articles.*') // active for articles.index / articles.edit / articles.anything

$item->meta(['a' => 'b']);
// same as
$item->a('b');

Testing

composer test

Navigation for Laravel was created by Félix Dorn under the MIT license.