Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Menu Laravel Package

lavary/laravel-menu

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require lavary/laravel-menu
    

    Publish the config file:

    php artisan vendor:publish --provider="Lavary\Menu\MenuServiceProvider"
    

    Run migrations:

    php artisan migrate
    
  2. First Menu Creation: Use the Menu facade to create a menu:

    use Lavary\Menu\Menu;
    
    Menu::make('main', function($menu) {
        $menu->add('Home', ['url' => '/']);
        $menu->add('About', ['url' => '/about']);
    });
    
  3. Display in Blade:

    {!! Menu::get('main') !!}
    

First Use Case: Dynamic Navigation

Create a footer menu dynamically based on user roles:

Menu::make('footer', function($menu) {
    $menu->add('Contact', ['url' => '/contact']);
    if (auth()->check()) {
        $menu->add('Dashboard', ['url' => '/dashboard']);
    }
});

Implementation Patterns

Menu Definition Workflows

  1. Static Menus: Define menus in a service provider's boot() method:

    public function boot()
    {
        Menu::make('main', function($menu) {
            $menu->add('Products', ['url' => '/products']);
            $menu->add('Services', ['url' => '/services']);
        });
    }
    
  2. Dynamic Menus: Use closures to conditionally build menus:

    Menu::make('user', function($menu) {
        if (auth()->user()->isAdmin()) {
            $menu->add('Admin Panel', ['url' => '/admin']);
        }
        $menu->add('Profile', ['url' => '/profile']);
    });
    
  3. Reusable Menu Components: Extract menu logic into a dedicated class:

    class NavigationBuilder
    {
        public static function buildMainMenu()
        {
            Menu::make('main', function($menu) {
                $menu->add('Home', ['url' => '/']);
                $menu->add('Blog', ['url' => '/blog']);
            });
        }
    }
    

Integration Tips

  1. Blade Directives: Create a custom Blade directive for cleaner syntax:

    Blade::directive('menu', function($expression) {
        return "<?php echo Lavary\Menu\Menu::get($expression); ?>";
    });
    

    Usage:

    @menu('main')
    
  2. Middleware Integration: Dynamically adjust menus based on middleware:

    public function handle($request, Closure $next)
    {
        Menu::make('main', function($menu) {
            $menu->add('Secure Area', ['url' => '/secure']);
        });
        return $next($request);
    }
    
  3. Caching: Cache menus for performance:

    Menu::make('main', function($menu) {
        // Menu logic
    })->cacheFor(60); // Cache for 60 minutes
    
  4. Localization: Use localization helpers to generate multi-language menus:

    Menu::make('main', function($menu) {
        $menu->add(__('Home'), ['url' => '/']);
        $menu->add(__('About'), ['url' => '/about']);
    });
    

Gotchas and Tips

Common Pitfalls

  1. Menu Not Updating:

    • Cause: Caching is enabled by default.
    • Fix: Clear cache with php artisan menu:clear or disable caching temporarily:
      Menu::make('main', function($menu) { /* ... */ })->cacheFor(0);
      
  2. Duplicate Menu Items:

    • Cause: Menus are recreated on every request without checking existing items.
    • Fix: Use Menu::get('menu_name') to check if a menu exists before recreating it.
  3. Active Item Logic:

    • Cause: Incorrect URL matching for active items.
    • Fix: Use Menu::get('main')->active to debug active item logic or manually set active items:
      $menu->add('Home', ['url' => '/', 'active' => request()->is('/')]);
      
  4. Nested Menu Performance:

    • Cause: Deeply nested menus can slow down rendering.
    • Fix: Limit nesting depth or use lazy-loading for submenus.

Debugging Tips

  1. Dump Menu Structure:

    dd(Menu::get('main')->toArray());
    
  2. Check Menu Existence:

    if (Menu::has('main')) {
        // Menu exists
    }
    
  3. Inspect Active Item:

    $activeItem = Menu::get('main')->active;
    dd($activeItem);
    

Configuration Quirks

  1. Default Cache Driver: The package uses Laravel's cache driver by default. Ensure your .env has a valid cache driver (e.g., file, redis).

  2. Menu Storage: Menus are stored in the menus table. Customize the table name in config/menu.php:

    'table' => 'custom_menu_items',
    
  3. Item ID Generation: By default, IDs are auto-generated. To manually set IDs:

    $menu->add('Home', ['url' => '/', 'id' => 'home']);
    

Extension Points

  1. Custom Menu Builders: Extend the Lavary\Menu\Builder class to add custom methods:

    class CustomMenuBuilder extends \Lavary\Menu\Builder
    {
        public function addCustomItem($title, $options)
        {
            // Custom logic
        }
    }
    

    Register the builder in AppServiceProvider:

    Menu::extend('custom', function() {
        return new CustomMenuBuilder();
    });
    
  2. Custom Renderers: Override the default renderer for custom HTML output:

    Menu::make('main', function($menu) {
        // Menu logic
    })->renderUsing(function($menu) {
        return '<ul class="custom-menu">' . $menu->render() . '</ul>';
    });
    
  3. Event Listeners: Listen to menu events for logging or analytics:

    Menu::get('main')->on('beforeRender', function($menu) {
        // Log menu rendering
    });
    
  4. Database Extensions: Add custom fields to menu items by extending the MenuItem model:

    class CustomMenuItem extends \Lavary\Menu\Models\MenuItem
    {
        protected $casts = [
            'custom_field' => 'boolean',
        ];
    }
    

    Update the config to use your custom model:

    'model' => \App\Models\CustomMenuItem::class,
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware