### Install Nova Menu Builder Package (Bash)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Installs the Nova Menu Builder package using Composer, publishes its configuration file, and runs the necessary database migrations to set up menu tables.
```bash
# Install the package
composer require outl1ne/nova-menu-builder
# Publish the configuration file
php artisan vendor:publish --tag=nova-menu-builder-config
# Run migrations
php artisan migrate
```
--------------------------------
### Get All Menus
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Retrieves all menus, optionally filtered by locale. The response includes nested menu items.
```APIDOC
## GET /api/menus
### Description
Retrieves all menus with their items formatted for API consumption. You can optionally specify a locale to filter the results.
### Method
GET
### Endpoint
/api/menus
### Query Parameters
- **locale** (string) - Optional - The locale code for filtering menus (e.g., 'en', 'fr'). Defaults to all locales if not provided.
### Response
#### Success Response (200)
- **menus** (array) - An array of menu objects, each containing its details and a list of `menuItems`.
#### Response Example
```json
[
{
"id": 1,
"name": "Header Navigation",
"slug": "header",
"locale": "en",
"menuItems": [
{
"id": 1,
"name": "Home",
"type": "static-url",
"value": "/",
"target": "_self",
"enabled": true,
"data": null,
"children": []
}
]
}
]
```
```
--------------------------------
### Build Navigation Component in PHP and JavaScript
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Fetch menu data using helper functions and integrate it into a frontend navigation component. This example demonstrates fetching header, footer, and sidebar menus and rendering them recursively.
```php
// app/Http/Controllers/NavigationController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class NavigationController extends Controller
{
public function index(Request $request)
{
$locale = app()->getLocale();
return response()->json([
'header' => nova_get_menu_by_slug('header', $locale),
'footer' => nova_get_menu_by_slug('footer', $locale),
'sidebar' => nova_get_menu_by_slug('sidebar', $locale),
]);
}
}
// routes/api.php
Route::get('/navigation', [NavigationController::class, 'index']);
```
```javascript
// Frontend JavaScript example (Vue.js)
// api/navigation.js
export async function fetchNavigation() {
const response = await fetch('/api/navigation');
return response.json();
}
// components/Navigation.vue
export default {
data() {
return {
headerMenu: null,
footerMenu: null,
};
},
async mounted() {
const navigation = await fetchNavigation();
this.headerMenu = navigation.header;
this.footerMenu = navigation.footer;
},
methods: {
renderMenuItem(item) {
return {
id: item.id,
label: item.name,
url: item.value,
target: item.target,
enabled: item.enabled,
icon: item.data?.icon,
children: item.children.map(child => this.renderMenuItem(child)),
};
},
},
};
```
--------------------------------
### Get Menu by Slug
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Retrieves a single menu identified by its unique slug. An optional locale parameter can be provided.
```APIDOC
## GET /api/menus/{slug}
### Description
Retrieves a single menu by its slug identifier. You can specify a locale to fetch the menu for a particular language.
### Method
GET
### Endpoint
/api/menus/{slug}
### Path Parameters
- **slug** (string) - Required - The unique slug identifier of the menu.
### Query Parameters
- **locale** (string) - Optional - The locale code for the menu (e.g., 'en'). Defaults to the first configured locale if not provided.
### Response
#### Success Response (200)
- **menu** (object) - The menu object, including its details and `menuItems`.
#### Error Response (404)
- **error** (string) - "Menu not found"
#### Response Example
```json
{
"id": 1,
"name": "Header Navigation",
"slug": "header",
"locale": "en",
"menuItems": [
{
"id": 1,
"name": "Home",
"type": "static-url",
"value": "/",
"target": "_self",
"enabled": true,
"data": null,
"children": []
}
]
}
```
```
--------------------------------
### Get Menu by ID
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Retrieves a single menu using its database ID. An optional locale parameter can be specified.
```APIDOC
## GET /api/menus/{id}
### Description
Retrieves a single menu by its database ID. You can optionally specify a locale to fetch the menu for a particular language.
### Method
GET
### Endpoint
/api/menus/{id}
### Path Parameters
- **id** (integer) - Required - The database ID of the menu.
### Query Parameters
- **locale** (string) - Optional - The locale code for the menu (e.g., 'en'). Defaults to 'en' if not provided.
### Response
#### Success Response (200)
- **menu** (object) - The menu object, containing its ID, name, slug, locale, and a list of `items`.
#### Error Response (404)
- **error** (string) - "Menu not found"
#### Response Example
```json
{
"id": 1,
"name": "Header Navigation",
"slug": "header",
"locale": "en",
"items": [
{
"id": 1,
"name": "Home",
"type": "static-url",
"value": "/",
"target": "_self",
"enabled": true,
"data": null,
"children": []
}
]
}
```
```
--------------------------------
### Install Nova Menu Builder Package
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
Installs the Nova Menu Builder package using Composer and publishes its configuration file for customization. This is the first step in integrating the package into a Laravel Nova project.
```bash
composer require outl1ne/nova-menu-builder
php artisan vendor:publish --tag=nova-menu-builder-config
```
--------------------------------
### Get All Menus via Helper Function in PHP
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
This PHP code shows how to use the globally registered `nova_get_menus()` helper function to retrieve all menus in an API-friendly format and return them as a JSON response.
```php
public function getMenus(Request $request) {
$menusResponse = nova_get_menus();
return response()->json($menusResponse);
}
```
--------------------------------
### Get All Menus (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Retrieves all menus, optionally filtered by locale, using the `nova_get_menus` helper function. This function is useful for fetching menu data formatted for API consumption. It returns an array of menu objects, each containing its items.
```php
use Illuminate\Http\Request;
public function getMenus(Request $request)
{
// Get all menus for all locales
$allMenus = nova_get_menus();
// Get all menus for a specific locale
$englishMenus = nova_get_menus('en');
return response()->json($englishMenus);
}
```
--------------------------------
### Get Menu by Slug (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Fetches a single menu based on its unique slug identifier, with an optional locale parameter. The `nova_get_menu_by_slug` function returns the menu object or null if not found. This is useful for retrieving specific navigation menus like headers or footers.
```php
use Illuminate\Http\Request;
public function getHeaderMenu(Request $request)
{
$locale = $request->get('locale', 'en');
// Get menu by slug
$headerMenu = nova_get_menu_by_slug('header', $locale);
if ($headerMenu === null) {
return response()->json(['error' => 'Menu not found'], 404);
}
return response()->json($headerMenu);
}
// Usage with automatic locale detection
$menu = nova_get_menu_by_slug('footer'); // Uses first configured locale
```
--------------------------------
### Get Menu by ID (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Retrieves a specific menu using its database ID, with an optional locale parameter. The `nova_get_menu_by_id` function returns the menu details or null if the menu does not exist. The response can be customized to include specific fields.
```php
use Illuminate\Http\Request;
public function getMenu($menuId, Request $request)
{
$locale = $request->get('locale', 'en');
// Get menu by database ID
$menu = nova_get_menu_by_id($menuId, $locale);
if ($menu === null) {
return response()->json(['error' => 'Menu not found'], 404);
}
return response()->json([
'id' => $menu['id'],
'name' => $menu['name'],
'slug' => $menu['slug'],
'locale' => $menu['locale'],
'items' => $menu['menuItems'],
]);
}
```
--------------------------------
### Get Single Menu by Slug or ID in PHP
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
This snippet illustrates how to fetch a single menu using helper functions like `nova_get_menu_by_slug()` or `nova_get_menu_by_id()`. These functions can optionally accept a locale and return null if the menu is not found.
```php
// Available helpers
nova_get_menu_by_slug($menuSlug, $locale = null)
nova_get_menu_by_id($menuId, $locale = null)
```
--------------------------------
### Query Menus Directly (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Demonstrates how to access and query the Menu model directly using Laravel's Eloquent. It shows how to retrieve the configured Menu model class, fetch all menus, load relationships like 'rootMenuItems', filter by locale, and format menus for API responses.
```php
use Outl1ne\MenuBuilder\MenuBuilder;
// Get the configured Menu model class
$menuClass = MenuBuilder::getMenuClass();
// Query menus
$menus = $menuClass::all();
// Get menu with root items
$menu = $menuClass::with('rootMenuItems')->where('slug', 'header')->first();
// Get menu items for a specific locale
$menuItems = $menu->rootMenuItems()
->where('locale', 'en')
->orderBy('order')
->get();
// Format menu for API response
$apiResponse = $menu->formatForAPI('en');
```
--------------------------------
### Configure Dynamic Locales in nova-menu.php (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Demonstrates setting up dynamic locale resolution for menu items in the nova-menu.php configuration file, using closures, callable strings, or simple function names.
```php
// config/nova-menu.php
return [
// Using a closure (not cacheable)
'locales' => function() {
return \App\Models\Language::where('active', true)
->pluck('name', 'code')
->toArray();
},
// Using a callable string (cacheable)
'locales' => '\App\Configuration\NovaMenuConfiguration@getLocales',
// Using a simple function name
'locales' => 'nova_lang_get_locales',
];
```
--------------------------------
### Query Menu Items (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Illustrates querying the MenuItem model directly for custom filtering and data retrieval. It covers fetching all enabled items, root-level items, items with their children, and accessing various attributes of a menu item.
```php
use Outl1ne\MenuBuilder\MenuBuilder;
// Get the configured MenuItem model class
$menuItemClass = MenuBuilder::getMenuItemClass();
// Get all enabled menu items
$enabledItems = $menuItemClass::enabled()->get();
// Get root-level items only
$rootItems = $menuItemClass::root()->get();
// Get items with their children relationship
$items = $menuItemClass::with('children')
->where('menu_id', 1)
->where('locale', 'en')
->whereNull('parent_id')
->orderBy('order')
->get();
// Access menu item attributes
foreach ($items as $item) {
echo $item->name; // Menu item name
echo $item->value; // Stored value
echo $item->displayValue; // Formatted display value
echo $item->customValue; // Processed value for API
echo $item->type; // Menu item type identifier
echo $item->enabled; // Boolean enabled state
echo $item->target; // Link target (_self, _blank)
echo $item->data; // Additional data array
echo $item->children; // Child menu items
}
```
--------------------------------
### Configure Menu Settings in nova-menu.php (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Defines core settings for Nova Menu Builder, including database table names, supported locales, menu zones (header, footer, sidebar) with their configurations, and available menu item types.
```php
// config/nova-menu.php
return [
// Database table names
'menus_table_name' => 'nova_menu_menus',
'menu_items_table_name' => 'nova_menu_menu_items',
// Available locales for menu items
'locales' => [
'en' => 'English',
'de' => 'German',
'fr' => 'French',
],
// Define available menu zones
'menus' => [
'header' => [
'name' => 'Header Navigation',
'unique' => true, // Only one menu with this slug allowed
'max_depth' => 3, // Maximum nesting level
'menu_item_types' => [], // Specific types for this menu
],
'footer' => [
'name' => 'Footer Navigation',
'unique' => true,
'max_depth' => 2,
],
'sidebar' => [
'name' => 'Sidebar Menu',
'unique' => false, // Multiple menus allowed
],
],
// Global menu item types
'menu_item_types' => [
\Outl1ne\MenuBuilder\MenuItemTypes\MenuItemTextType::class,
\Outl1ne\MenuBuilder\MenuItemTypes\MenuItemStaticURLType::class,
\App\MenuItemTypes\PageLinkType::class, // Custom type
],
// Display options
'show_duplicate' => true,
'collapsed_as_default' => true,
// Optional model/controller overrides
'menu_model' => \Outl1ne\MenuBuilder\Models\Menu::class,
'menu_item_model' => \Outl1ne\MenuBuilder\Models\MenuItem::class,
'controller' => \Outl1ne\MenuBuilder\Http\Controllers\MenuController::class,
'resource' => \Outl1ne\MenuBuilder\Nova\Resources\MenuResource::class,
];
```
--------------------------------
### Generate Custom Menu Item Type with Artisan (Bash)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Scaffolds a new custom menu item type class using the 'menubuilder:type' Artisan command. The command prompts for necessary details like type name, identifier, and base type, and generates the file in the specified directory.
```bash
# Generate a new custom menu item type
php artisan menubuilder:type
# The command will prompt for:
# - Type name (e.g., "Product Link")
# - Type identifier (e.g., "product-link")
# - Base type (select or text)
# Generated file will be created at:
# app/Nova/MenuBuilderTypes/ProductLinkType.php
```
--------------------------------
### Run Nova Menu Builder Migrations
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
Executes the database migrations required by the Nova Menu Builder package. This command creates the necessary tables in your database to store menu and menu item data. Ensure configuration is complete before running.
```bash
php artisan migrate
```
--------------------------------
### Create Static URL Menu Item Type (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Defines a custom menu item type for handling static URLs, extending the `BaseMenuItemType` class. This type includes validation rules for the URL and methods to define its identifier, display name, and how its value is processed.
```php
namespace App\MenuItemTypes;
use Outl1ne\MenuBuilder\MenuItemTypes\BaseMenuItemType;
class ExternalLinkType extends BaseMenuItemType
{
public static function getIdentifier(): string
{
return 'external-link';
}
public static function getName(): string
{
return 'External Link';
}
public static function getType(): string
{
return 'static-url';
}
public static function getRules(): array
{
return [
'value' => 'required|url|max:255',
];
}
public static function getDisplayValue($value, ?array $data, $locale)
{
return "External: {$value}";
}
public static function getValue($value, ?array $data, $locale)
{
return $value;
}
}
```
--------------------------------
### Configure Custom Locale Display in Nova
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Customizes the display of locale options within the Nova interface by providing HTML snippets, typically for flag images. This configuration is done within the `NovaServiceProvider` by using `Nova::provideToScript` to pass custom data to the Nova frontend.
```php
// app/Providers/NovaServiceProvider.php
use Laravel\Nova\Nova;
public function boot()
{
Nova::serving(function () {
Nova::provideToScript([
'customLocaleDisplay' => [
'en' => '',
'de' => '',
'fr' => '',
'es' => '',
],
]);
});
}
```
--------------------------------
### Create Select Type for Pages (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Defines a custom menu item type 'Page Link' that provides a dropdown of selectable pages from the database. It extends `MenuItemSelectType` and implements methods to fetch page options, display values, and define validation rules. Requires the `Page` model and `Outl1neMenuBuilder` package.
```php
// app/MenuItemTypes/PageLinkType.php
namespace App\MenuItemTypes;
use App\Models\Page;
use Outl1ne\MenuBuilder\MenuItemTypes\MenuItemSelectType;
class PageLinkType extends MenuItemSelectType
{
public static function getIdentifier(): string
{
return 'page-link';
}
public static function getName(): string
{
return 'Page Link';
}
/**
* Get options for the select dropdown.
* Returns [key => label] pairs where key is stored as value.
*/
public static function getOptions($locale): array
{
return Page::where('locale', $locale)
->where('published', true)
->orderBy('title')
->pluck('title', 'id')
->toArray();
}
/**
* Display value shown in the menu builder interface.
*/
public static function getDisplayValue($value, ?array $data, $locale)
{
$page = Page::find($value);
return $page ? "Page: {$page->title}" : 'Page not found';
}
/**
* Value returned to the frontend API.
*/
public static function getValue($value, ?array $data, $locale)
{
$page = Page::find($value);
return $page ? $page->slug : null;
}
public static function getRules(): array
{
return [
'value' => 'required|exists:pages,id',
];
}
}
```
--------------------------------
### Register MenuBuilder Tool in NovaServiceProvider (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Registers the MenuBuilder tool within the NovaServiceProvider's tools method. Allows customization of the sidebar title, icon, and visibility.
```php
// app/Providers/NovaServiceProvider.php
use Outl1ne\MenuBuilder\MenuBuilder;
public function tools()
{
return [
MenuBuilder::make()
->title('Navigation') // Custom sidebar title
->icon('menu') // Custom heroicon name
->hideMenu(false), // Show/hide from sidebar
];
}
```
--------------------------------
### Publish Nova Menu Builder Migrations (Optional)
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
Publishes the migration files for the Nova Menu Builder package. This is an optional step, useful if you need to customize the default migration structure or models before they are run.
```bash
php artisan vendor:publish --tag=nova-menu-builder-migrations
```
--------------------------------
### Override Menu Controller in PHP
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Create a custom controller that extends the base MenuController to add new endpoints or modify existing behavior. This is useful for custom filtering, data manipulation, or adding specific menu-related actions.
```php
// app/Http/Controllers/CustomMenuController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Outl1ne\MenuBuilder\Http\Controllers\MenuController;
use Outl1ne\MenuBuilder\MenuBuilder;
class CustomMenuController extends MenuController
{
// Override existing method
public function getMenus(Request $request)
{
$menuModel = MenuBuilder::getMenuClass();
$query = $menuModel::query();
// Add custom filtering
if ($request->has('category')) {
$query->where('category_id', $request->category);
}
if ($request->boolean('notEmpty')) {
$query->whereHas('rootMenuItems');
}
return $query->get()->map(function ($menu) {
return [
'id' => $menu->id,
'title' => "{$menu->name} ({$menu->slug})",
'name' => $menu->name,
'slug' => $menu->slug,
'itemCount' => $menu->rootMenuItems()->count(),
];
});
}
// Add custom endpoint
public function exportMenu($menuId)
{
$menu = MenuBuilder::getMenuClass()::with('rootMenuItems')->find($menuId);
if (!$menu) {
return response()->json(['error' => 'Menu not found'], 404);
}
return response()->json([
'menu' => $menu->toArray(),
'exported_at' => now()->toIso8601String(),
]);
}
}
// Register in config/nova-menu.php
// 'controller' => \App\Http\Controllers\CustomMenuController::class,
```
--------------------------------
### Create Dynamic Enabled State Menu Item Type (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Defines a custom menu item type 'ScheduledLinkType' that dynamically determines its enabled state based on 'visible_from' and 'visible_until' dates. It uses Carbon for date comparisons and Laravel Nova's DateTime field for input.
```php
// app/MenuItemTypes/ScheduledLinkType.php
namespace App\MenuItemTypes;
use Carbon\Carbon;
use Laravel\Nova\Fields\DateTime;
use Outl1ne\MenuBuilder\MenuItemTypes\BaseMenuItemType;
class ScheduledLinkType extends BaseMenuItemType
{
public static function getIdentifier(): string
{
return 'scheduled-link';
}
public static function getName(): string
{
return 'Scheduled Link';
}
public static function getType(): string
{
return 'static-url';
}
public static function getFields(): array
{
return [
DateTime::make('Visible From', 'visible_from')
->help('Leave empty for immediate visibility'),
DateTime::make('Visible Until', 'visible_until')
->help('Leave empty for permanent visibility'),
];
}
/**
* Dynamically determine if menu item should be enabled.
*/
public static function getEnabledValue($value, ?array $data, $locale)
{
$now = Carbon::now();
$visibleFrom = isset($data['visible_from'])
? Carbon::parse($data['visible_from'])
: null;
$visibleUntil = isset($data['visible_until'])
? Carbon::parse($data['visible_until'])
: null;
if ($visibleFrom && $now->lt($visibleFrom)) {
return false; // Not yet visible
}
if ($visibleUntil && $now->gt($visibleUntil)) {
return false; // No longer visible
}
return true;
}
public static function getRules(): array
{
return [
'value' => 'required|url|max:255',
'data->visible_from' => 'nullable|date',
'data->visible_until' => 'nullable|date|after:data->visible_from',
];
}
}
```
--------------------------------
### Configure Nova Menu Builder Table Names and Locales
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
Sets up the database table names for menus and menu items, and defines the project's locales. This configuration is crucial for the package's data management and localization features. Custom table names should be set before running migrations.
```php
// in config/nova-menu.php
return [
// ...
'menus_table_name' => 'nova_menu_menus',
'menu_items_table_name' => 'nova_menu_menu_items',
'locales' => ['en' => 'English'],
'menus' => [
// 'header' => [
// 'name' => 'Header',
// 'unique' => true,
// 'menu_item_types' => []
// ]
],
'menu_item_types' => [],
// ...
];
```
--------------------------------
### Create Type with Custom Fields (PHP)
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Defines a custom menu item type 'Advanced Link' that includes additional Nova fields for storing extra data like icons or CSS classes. It extends `BaseMenuItemType` and uses Nova field classes to define the interface. Includes methods for defining fields, validation rules, display values, and data transformation. Requires Laravel Nova and Outl1neMenuBuilder.
```php
// app/MenuItemTypes/AdvancedLinkType.php
namespace App\MenuItemTypes;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\Select;
use Laravel\Nova\Fields\Boolean;
use Outl1ne\MenuBuilder\MenuItemTypes\BaseMenuItemType;
class AdvancedLinkType extends BaseMenuItemType
{
public static function getIdentifier(): string
{
return 'advanced-link';
}
public static function getName(): string
{
return 'Advanced Link';
}
public static function getType(): string
{
return 'static-url';
}
/**
* Define custom Nova fields for this menu item type.
*/
public static function getFields(): array
{
return [
Text::make('Icon Class', 'icon')
->help('FontAwesome or custom icon class'),
Text::make('CSS Classes', 'classes')
->help('Additional CSS classes for styling'),
Select::make('Style', 'style')
->options([
'default' => 'Default',
'primary' => 'Primary Button',
'secondary' => 'Secondary Button',
'highlight' => 'Highlighted',
]),
Boolean::make('Open in Modal', 'modal')
->help('Open link in a modal window'),
];
}
public static function getRules(): array
{
return [
'value' => 'required|url|max:255',
'data->icon' => 'nullable|string|max:50',
'data->classes' => 'nullable|string|max:100',
'data->style' => 'nullable|in:default,primary,secondary,highlight',
];
}
public static function getDisplayValue($value, ?array $data, $locale)
{
$icon = $data['icon'] ?? '';
return $icon ? "[{$icon}] {$value}" : $value;
}
public static function getValue($value, ?array $data, $locale)
{
return $value;
}
/**
* Transform data for frontend API consumption.
*/
public static function getData($data = null)
{
if ($data === null) {
return null;
}
return [
'icon' => $data['icon'] ?? null,
'classes' => $data['classes'] ?? null,
'style' => $data['style'] ?? 'default',
'modal' => $data['modal'] ?? false,
];
}
}
```
--------------------------------
### Render Menus in Laravel Blade Templates
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Integrates Nova Menu Builder menus into Laravel Blade views using a custom Blade component. The component fetches menu data by slug and locale, then renders it as an HTML navigation structure. It supports nested menus and custom item attributes like target and classes.
```php
// app/View/Components/Navigation.php
namespace App\View\Components;
use Illuminate\View\Component;
class Navigation extends Component
{
public $menu;
public $locale;
public function __construct(string $slug, ?string $locale = null)
{
$this->locale = $locale ?? app()->getLocale();
$this->menu = nova_get_menu_by_slug($slug, $this->locale);
}
public function render()
{
return view('components.navigation');
}
}
```
```blade
{{-- resources/views/components/navigation.blade.php --}}
@if($menu && count($menu['menuItems']) > 0)
@endif
{{-- Usage in layout --}}
```
--------------------------------
### Override Menu Model in PHP
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Extend the base Menu model to add custom attributes, relationships, or modify API formatting. This allows for enhanced menu data representation and integration with other parts of your application.
```php
// app/Models/Menu.php
namespace App\Models;
use Outl1ne\MenuBuilder\Models\Menu as BaseMenu;
class Menu extends BaseMenu
{
protected $appends = ['item_count'];
public function getItemCountAttribute()
{
return $this->rootMenuItems()->count();
}
// Add custom relationships
public function category()
{
return $this->belongsTo(\App\Models\Category::class);
}
// Override formatForAPI for custom response
public function formatForAPI($locale)
{
$data = parent::formatForAPI($locale);
$data['category'] = $this->category?->name;
return $data;
}
}
// Register in config/nova-menu.php
// 'menu_model' => \App\Models\Menu::class,
```
--------------------------------
### Custom Menu Item Types - External Link
Source: https://context7.com/outl1ne/nova-menu-builder/llms.txt
Defines a custom menu item type for handling external URLs, including validation rules and display logic.
```APIDOC
## Custom Menu Item Type: External Link
### Description
This section details how to create a custom menu item type for handling external links. It defines the identifier, display name, type, validation rules, and how the value is processed.
### Identifier
`external-link`
### Name
External Link
### Type
`static-url`
### Validation Rules
```php
[
'value' => 'required|url|max:255',
]
```
### Display Value Logic
Returns "External: " prepended to the URL.
### Value Processing Logic
Returns the provided URL value directly.
```
--------------------------------
### Configure Locales for Nova Menu Builder
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
Defines the available locales for menu localization within the Nova Menu Builder configuration file. This can be done directly, using a closure, or by referencing a specific class method or helper function.
```php
// 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',
// ...
];
```
--------------------------------
### Define Custom Menu Item Type Methods in PHP
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
This section details the methods to override when creating a custom menu item type. These methods control the identifier, display name, options, display value, enabled status, front-end value, fields, rules, and data for the custom menu item.
```php
/**
* 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;
}
/**
* 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.
*/
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;
}
```
--------------------------------
### Register Nova Menu Builder Tool in NovaServiceProvider
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
Registers the Nova Menu Builder tool within the NovaServiceProvider. This makes the menu builder accessible in the Laravel Nova administration panel. Optional parameters like title and icon can be customized.
```php
// in app/Providers/NovaServiceProvider.php
public function tools()
{
return [
// ...
\Outl1ne\MenuBuilder\MenuBuilder::make()
->title('Menus') // Define a new name for sidebar
->icon('adjustments') // Customize menu icon, supports heroicons
->hideMenu(false) // Hide MenuBuilder defined MenuSection.
];
}
```
--------------------------------
### Customize Locale Display in Laravel Nova
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
This PHP snippet demonstrates how to customize the display of locales in Nova by using Nova::provideToScript in the NovaServiceProvider. It allows mapping locale codes to custom HTML elements, such as flag images.
```php
// in app/Providers/NovaServiceProvider.php
public function boot()
{
Nova::serving(function () {
Nova::provideToScript([
// ...
'customLocaleDisplay' => [
'en' => ,
'et' => ,
]
]);
});
}
```
--------------------------------
### Register Custom Menu Item Type in Laravel Nova
Source: https://github.com/outl1ne/nova-menu-builder/blob/main/README.md
This snippet shows how to register a custom menu item type by extending the BaseMenuItemType class and adding its class to the 'menu_item_types' array in the nova-menu.php config file.
```php
// in config/nova-menu.php
return [
// ...
'menu_item_types' => [
\App\MenuItemTypes\CustomMenuItemType::class,
],
// ...
];
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.