Search by

versioon / nova-menu-builder

Tarpsvo

This Laravel Nova package allows you to create and manage menus and menu items.

Package info

github.com/Versioon/nova-menu-builder

Homepage

Issues

pkg:composer/versioon/nova-menu-builder

Statistics

Installs: 4

Dependents: 0

Suggesters: 0

Stars: 242


README

Latest Version on Packagist Total Downloads

This Laravel Nova package allows you to create and manage menus and menu items.

Requirements

  • php: >=8.1
  • laravel/nova: ^5.0

Features

  • Menu management
  • Menu items management
    • Drag-and-drop nesting and re-ordering
    • Changes are highlighted and only saved together with the menu, removed items can be restored until then
    • Items can be copied from other menus
  • Custom menu item types
    • Select types, ie links to pages or products
    • Custom fields
    • menubuilder:type command to create new types
  • Fully localizable
    • Items can be in multiple locales and have separate content in some of them
    • A locale can be pre-filled with the items of another one

Screenshots

Menu items. The badges on the right list the locales of items that aren't in all of them, those next to the value list the locales where an item has separate content.

Menu items

Editing a menu item with custom fields, whose content is shared between locales or separate in one of them:

Menu item with shared content Menu item with separate content in Estonian

Upgrading

See UPGRADING.md. Version 10 moved the package from outl1ne/nova-menu-builder to versioon/nova-menu-builder.

Installation and Setup

Installing the package

Install the package in a Laravel Nova project via Composer, edit the configuration file and run migrations.

# Install the package
composer require versioon/nova-menu-builder

# Publish the configuration file and edit it to your preference
# NB! If you want custom table names, configure them before running the migrations.
php artisan vendor:publish --tag=nova-menu-builder-config

Register the tool with Nova in the tools() method of the NovaServiceProvider:

// in app/Providers/NovaServiceProvider.php

public function tools()
{
    return [
        // ...
        \Versioon\MenuBuilder\MenuBuilder::make()
            // Optional customization
            ->title('Menus') // Name in the sidebar
            ->icon('bars-4') // Sidebar icon, supports Heroicons
            ->hideMenu(false), // Hide the sidebar item
    ];
}

Setting up

After publishing the configuration file, you have to make some required changes in the config:

# Choose table names of your liking by editing the two key/values:
'menus_table_name' => 'nova_menu_menus',
'menu_items_table_name' => 'nova_menu_menu_items',

# Define the locales for your project:
# If your project doesn't have localization, you can just leave it as it is.
# When there's just one locale, anything related to localization isn't displayed.
'locales' => ['en' => 'English'],

# Define the list of possible menus (ie 'footer', 'header', 'main-menu'):
'menus' => [
    // 'header' => [
    //     'name' => 'Header',
    //     'unique' => true, // Only one menu of this type can be created
    //     'max_depth' => 10, // How deep items can be nested
    //     'menu_item_types' => [], // Types that only this menu has
    // ]
],

# Menu item types that all menus have. Add your custom types here:
'menu_item_types' => [
    \Versioon\MenuBuilder\MenuItemTypes\MenuItemTextType::class,
    \Versioon\MenuBuilder\MenuItemTypes\MenuItemStaticURLType::class,
],

The config also lets you:

  • hide the option to copy items from other menus (show_duplicate)
  • display sub-items expanded by default (collapsed_as_default)
  • replace the controller, Nova resource and models (controller, resource, menu_model, menu_item_model)

Next, just run the migrations and you're set.

# Run the automatically loaded migrations
php artisan migrate

Optionally publish migrations

This is only useful if you want to change the migrations. If you wish to use the menu builder as it comes out of the box, you don't need them. Set auto_load_migrations to false in the config, so that they don't run twice.

# Publish migrations to change them (optional)
php artisan vendor:publish --tag=nova-menu-builder-migrations

Usage

Locales configuration

You can define the locales for the menus in the config file, as shown below.

// in config/nova-menu.php

return [
  // ...
  'locales' => [
    'en' => 'English',
    'et' => 'Estonian',
  ],

  // or using a closure (not cacheable):

  'locales' => function() {
    return nova_lang_get_locales();
  }

  // or if you want to use a function, but still be able to cache it:

  'locales' => '\App\Configuration\NovaMenuConfiguration@getLocales',

  // or

  'locales' => 'nova_lang_get_locales',
  // ...
];

Items in multiple locales

A menu item can be in any number of locales. Its position, type, target and state (enabled or disabled) are always shared, names are always kept per locale.

The content (value and custom fields) is shared, unless "Separate content for ..." is turned on when editing the item in a locale. Changes made in the other locales then no longer apply to it, until it's turned off again.

Sub-items have their own locales. In a locale that their parent isn't in they're hidden, until the parent is added to it.

$item->locales; // ['en', 'et']
$item->name; // The shared name
$item->forLocale('et')->name; // The name in Estonian

Custom menu item types

Menu builder allows you to create custom menu item types with custom fields. Create one with the command below, which adds it to app/Nova/MenuBuilderTypes, and register it in the config file.

php artisan menubuilder:type PageLinkType
// in config/nova-menu.php

return [
  // ...
  'menu_item_types' => [
    // ...
    \App\Nova\MenuBuilderTypes\PageLinkType::class,
  ],
  // ...
];

A type extends one of the following classes, which decide what's entered as the value:

  • MenuItemTextType: nothing, ie for headings
  • MenuItemStaticURLType: a URL
  • MenuItemSelectType: an option from getOptions(), ie a page or product

They're in the Versioon\MenuBuilder\MenuItemTypes namespace. For example, the type in the screenshots above:

namespace App\Nova\MenuBuilderTypes;

use App\Models\Page;
use Laravel\Nova\Fields\Boolean;
use Laravel\Nova\Fields\Select;
use Laravel\Nova\Fields\Text;
use Versioon\MenuBuilder\MenuItemTypes\MenuItemSelectType;

class PageLinkType extends MenuItemSelectType
{
    public static function getIdentifier(): string
    {
        return 'page';
    }

    public static function getName(): string
    {
        return 'Page link';
    }

    public static function getOptions($locale): array
    {
        return Page::pluck('title', 'slug')->all();
    }

    public static function getDisplayValue($value, ?array $data, $locale)
    {
        return 'Page: ' . Page::firstWhere('slug', $value)?->title;
    }

    public static function getFields(): array
    {
        return [
            Select::make('Icon')->options(['home' => 'Home', 'briefcase' => 'Briefcase'])->nullable(),
            Text::make('Badge')->help('Short label next to the link, ie "New"'),
            Boolean::make('Highlighted'),
        ];
    }
}

The values of custom fields are stored in the item's data, ie ['icon' => 'briefcase', 'badge' => 'Hiring', 'highlighted' => true]. Fields in a Panel are nested under the panel's name.

These are all the methods that a type can override:

/**
 * Get the menu link identifier that can be used to tell different custom
 * links apart (ie 'page' or 'product').
 *
 * @return string
 **/
public static function getIdentifier(): string {
    // Example usecase
    // return 'page';
    return '';
}

/**
 * Get menu link name shown in  a dropdown in CMS when selecting link type
 * ie ('Product Link').
 *
 * @return string
 **/
public static function getName(): string {
    // Example usecase
    // return 'Page Link';
    return '';
}

/**
 * Get list of options shown in a select dropdown.
 *
 * Should be a map of [key => value, ...], where key is a unique identifier
 * and value is the displayed string.
 *
 * @return array
 **/
public static function getOptions($locale): array {
    // Example usecase
    // return Page::all()->pluck('name', 'id')->toArray();
    return [];
}

/**
 * Get the subtitle value shown in CMS menu items list.
 *
 * @param $value
 * @param $data The data from item fields.
 * @param $locale
 * @return string
 **/
public static function getDisplayValue($value, ?array $data, $locale) {
    // Example usecase
    // return 'Page: ' . Page::find($value)->name;
    return $value;
}

/**
 * Get the enabled value
 *
 * @param $value
 * @param $data The data from item fields.
 * @param $locale
 * @return string
*/
public static function getEnabledValue($value, ?array $data, $locale)
{
  return true;
}

/**
 * Get the value of the link visible to the front-end.
 *
 * Can be anything. It is up to you how you will handle parsing it.
 *
 * This will only be called when using the nova_get_menu()
 * and nova_get_menus() helpers or when you call formatForAPI()
 * on the Menu model.
 *
 * @param $value The key from options list that was selected.
 * @param $data The data from item fields.
 * @param $locale
 * @return any
 */
public static function getValue($value, ?array $data, $locale)
{
    return $value;
}

/**
 * Called when an item is added to a locale, ie to set its translated name.
 *
 * Changes of the name, value and data are only applied to the given locale, others are ignored.
 * If the value or data is changed, the locale has separate content.
 * The item must not be saved.
 */
public static function localizeItem($item, string $locale): void
{
    // Example usecase
    // $item->name = Page::find($item->value)->getTranslation('name', $locale);
}

/**
 * Get the fields displayed by the resource.
 *
 * @return array An array of fields.
 */
public static function getFields(): array
{
    return [];
}

/**
 * Get the rules for the resource.
 *
 * @return array A key-value map of attributes and rules, ie ['value' => 'required', 'badge' => 'max:20'].
 */
public static function getRules(): array
{
    return [];
}

/**
 * Get data of the link visible to the front-end.
 *
 * Can be anything. It is up to you how you will handle parsing it.
 *
 * This will only be called when using the nova_get_menu()
 * and nova_get_menus() helpers or when you call formatForAPI()
 * on the Menu model.
 *
 * @param null $data Field values
 * @return any
 */
public static function getData($data = null)
{
    return $data;
}

Custom locale display

To customize how the locales are displayed in the menu builder, you can use Nova::provideToScript to pass customLocaleDisplay as in the example below. The values are HTML.

// in app/Providers/NovaServiceProvider.php

public function boot()
{
    Nova::serving(function () {
        Nova::provideToScript([
            // ...
            'customLocaleDisplay' => [
                'en' => '<img src="/flag-en.png" alt="English">',
                'et' => '<img src="/flag-et.png" alt="Estonian">',
            ],
        ]);
    });
}

Returning the menus in a JSON API

nova_get_menus()

A helper function nova_get_menus is globally registered in this package which returns all the menus including their menu items in an API friendly format. If a locale is passed, it returns the menus in that locale. Otherwise there's one entry per menu and locale.

public function getMenus(Request $request) {
    return response()->json(nova_get_menus($request->query('locale')));
}

Get single menu via identifier

// Available helpers
nova_get_menu_by_slug($menuSlug, $locale = null)
nova_get_menu_by_id($menuId, $locale = null)

To get a single menu, you can use the available helper functions.
Returns null if no menu with the identifier is found or returns the menu if it is found. If no locale is passed, the helper will automatically choose the first configured locale.

Format

Menus only contain the items that are in the locale, with their values in that locale. Disabled items are included, with enabled set to false.

{
  "id": 1,
  "name": "Header",
  "slug": "header",
  "locale": "et",
  "menuItems": [
    {
      "id": 6,
      "name": "Meist",
      "type": "page",
      "value": "about",
      "target": "_self",
      "enabled": true,
      "data": [],
      "children": [
        {
          "id": 7,
          "name": "Karjäär",
          "type": "page",
          "value": "careers",
          "target": "_self",
          "enabled": true,
          "data": { "icon": "briefcase", "badge": "Värbame", "highlighted": true },
          "children": []
        }
      ]
    }
  ]
}

type is the type's getIdentifier(), value and data are what its getValue() and getData() return.

Credits

License

Nova Menu Builder is open-sourced software licensed under the MIT license.