PHPackages                             vespakoen/menu - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. vespakoen/menu

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

vespakoen/menu
==============

Managing menus the easy way.

3.0.5(5y ago)27887.0k62[2 issues](https://github.com/vespakoen/menu/issues)[2 PRs](https://github.com/vespakoen/menu/pulls)5MITPHPPHP &gt;=5.4.0CI failing

Since Sep 24Pushed 5y ago26 watchersCompare

[ Source](https://github.com/vespakoen/menu)[ Packagist](https://packagist.org/packages/vespakoen/menu)[ RSS](/packages/vespakoen-menu/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (7)Versions (27)Used By (5)

Menu
====

[](#menu)

[![Build Status](https://camo.githubusercontent.com/1178be83d32255f8598dfa425b7d195922eb6aa80f6fea546ea9055126c6c1da/68747470733a2f2f7365637572652e7472617669732d63692e6f72672f76657370616b6f656e2f6d656e752e706e673f6272616e63683d6d6173746572)](http://travis-ci.org/vespakoen/menu)[![Total Downloads](https://camo.githubusercontent.com/dcc73330971595b1ac2ce7db573194e565bfdb9861e0e6f16a426e333c6010d4/68747470733a2f2f706f7365722e707567782e6f72672f76657370616b6f656e2f6d656e752f642f746f74616c2e737667)](https://packagist.org/packages/vespakoen/menu)[![Latest Stable Version](https://camo.githubusercontent.com/b03d9eabf5e3ca29b69ab615b90d2f6e12c21fabcd53321dc8b102669256b922/68747470733a2f2f706f7365722e707567782e6f72672f76657370616b6f656e2f6d656e752f762f737461626c652e737667)](https://packagist.org/packages/vespakoen/menu)[![Latest Unstable Version](https://camo.githubusercontent.com/164ce5a4efcac3025dc41f3f67cf82ce05c0fa427df354ecbc99c3002c4a00d7/68747470733a2f2f706f7365722e707567782e6f72672f76657370616b6f656e2f6d656e752f762f756e737461626c652e737667)](https://packagist.org/packages/vespakoen/menu)[![License](https://camo.githubusercontent.com/e5f03a01babeee13bf58cf96cdae8d3e3d9b1a54827a92b69bf0d68b0ea82511/68747470733a2f2f706f7365722e707567782e6f72672f76657370616b6f656e2f6d656e752f6c6963656e73652e737667)](https://packagist.org/packages/vespakoen/menu)

[API Docs](http://vespakoen.github.io/menu/)

Are you the type of person that writes menus by hand in view files or do you find yourself looking for the best place to store links to pages on your website? then Menu is for you!

Quick overview example
======================

[](#quick-overview-example)

```
$menu = Menu::handler('mailbox');

// items
$menu
    ->add('contacts', 'Contacts')
    ->add('inbox', 'Inbox')
    ->raw(null, null, ['class' => 'divider'])
    ->add('folders', 'Folders', Menu::items()
        ->prefixParents()
        ->add('urgent', 'Urgent') // with prefix: /folders/urgent
        ->add('sent', 'Sent')
        ->add('deleted', 'Deleted')
    );

// styling
$menu
    ->addClass('nav navbar-nav')
    ->getItemsByContentType(Menu\Items\Contents\Link::class)
    ->map(function($item) {
        if ( $item->isActive() )  {
            $item->addClass('active');
        }
    });
```

`{!! $menu !!}` will output:

```

    Contacts

    Inbox

    Folders

        Urgent

        Sent

        Deleted

```

Key concepts
============

[](#key-concepts)

Item lists
----------

[](#item-lists)

An item list is what a menu is all about and it should be pretty self explanatory because it simply stores a list of items. there are some configurations available for an item list. You can, for example set the HMTL element that will be used to render the list, prefix every item in the list with all the parent's url segments, and a lot more. We will explore these options later.

Menu handlers
-------------

[](#menu-handlers)

Menu handlers allow us to create and interact with item lists and act as a place to store and retrieve our menus. Because we are able to interact with multiple item lists at the same time some interesting possibilities become available to us.

Items
-----

[](#items)

The Menu package has 2 types of items available out of the box.

- Link For creating links to other pages
- Raw Be free to add anything you like in the item. This type is usually used for dividers, titles etc.

The HTML element and attributes for the item can also be changed, more on this topic later.

Installing
==========

[](#installing)

Laravel 3
---------

[](#laravel-3)

Install Menu via the artisan command line tool. Open the terminal and navigate to your Laravel project's root. Now type the following command :

```
php artisan bundle:install menu
```

To let Laravel know the Laravel Menu package should be started, open up `application/packages.php` and add the following lines to the packages array.

```
'menu' => array('auto' => true),
```

Laravel 4
---------

[](#laravel-4)

Add this to your `composer.json` file's `"require"` :

```
"vespakoen/menu": "2.*"
```

And add the following to your `app/config/app.php` file :

- In the Service Providers array : `'Menu\MenuServiceProvider',`
- In the aliases array : `'Menu' => 'Menu\Menu',`

Laravel 5
---------

[](#laravel-5)

Add this to your `composer.json` file's `"require"` :

```
"vespakoen/menu": "3.*"
```

And add the following to your `config/app.php` file :

- In the Service Providers array : `'Menu\MenuServiceProvider',`
- In the aliases array : `'Menu' => 'Menu\Menu',`

Lastly, run the following from your project's root dir:

```
php artisan vendor:publish

```

Basic usage
===========

[](#basic-usage)

First, let's load some pages into the menu. We will do this by utilising the `hydrate` method.

```
Menu::handler('main')->hydrate(function()
  {
    return Page::with('translation')
      ->where('group', '=', 'main')
      ->get();
  },
  function($children, $item)
  {
    $children->add($item->translation->slug, $item->translation->name, Menu::items($item->as));
  });

/* the hydrate method takes these arguments
  $resolver       Closure     A callback to resolve results
  $decorator      Closure     A callback that gets called for every result fetched from the resolver with the corresponding ItemList and result as the arguments
  $idField        integer (default = 'id')           the property on the result that contains the id
  $parentIdField  integer (default = 'parent_id')    the property on the result that contains the parent id
  $parentId       integer (default = 0)              the parentId to start hydrating from
*/
```

Now that we have loaded our pages into the menu, and even identified every menu item with a name (via `Menu::items($item->as)`) a lot of options are available to us.

Find a node by it's name and add a subitem.

```
Menu::find('users')
  ->add('users/create', 'Create new user');
```

Add some properties to the root node

```
Menu::handler('main')
  ->addClass('nav navbar-nav');
```

Get all `ItemList`s at a certain depth and add a class

```
Menu::handler('main')
  ->getItemListsAtDepth(0)
  ->addClass('level-1');
```

Get all `ItemList`s at a depth range and change the element

```
Menu::handler('main')
  ->getItemListsAtDepthRange(0,2)
  ->setElement('div');
```

Get all `Item`s at a certain depth and add a class

```
Menu::handler('main')
  ->getItemsAtDepth(0)
  ->addClass('level-1');
```

Get `Item`s by it's content type and use the map function to walk over the results and perform actions based on gathered information

```
Menu::handler('main')
  ->getItemsByContentType('Menu\Items\Contents\Link')
  ->map(function($item)
  {
    if($item->isActive() && $item->hasChildren())
    {
      $item->addClass('is-active-link-with-children');
    }

    if($item->getContent()->getUrl() == 'home')
    {
      $item->addClass('is-home');
    }
  });
```

Get all `ItemList`s and add a class to them if they have children

```
Menu::handler('main')
  ->getAllItemLists()
  ->map(function($itemList)
  {
    if($itemList->hasChildren())
    {
      $itemList->addClass('has-children');
    }
  });
```

Breadcrumbs
===========

[](#breadcrumbs)

Breadcrumb hell is a thing of the past.

Bootstrap ready breadcrums are as easy as this

```
Menu::handler('main')
    ->breadcrumbs()
    ->setElement('ol')
    ->addClass('breadcrumb');
```

The breadcrumbs method searches all handlers and returns a plain old ItemList, that you can manipulate. If you call the breadcrumbs method directly on the Menu class, it will search all your handlers for breadcrumbs, and by default will return the first match. However, there might be cases where you want to choose the breadcrumbs out of the ones it found, for this you can provide a callback method as the first argument.

And example is shown below:

```
Menu::breadcrumbs(function($itemLists)
    {
      return $itemLists[0]; // returns first match
    })
    ->setElement('ol')
    ->addClass('breadcrumb');
```

Diving deeper
=============

[](#diving-deeper)

The Laravel Menu packages consists of a couple of classes, but you can interact with all of them via the *Menu* class. Let's take a look at the **handler** method. it takes a string or an array as the only argument, the string(s) given are the names for the item lists we want to retrieve. If an itemlist we asked for didn't exist yet, it will create it for us. After the menu class has found and created the item lists we want, it will hand back a menuhandler that handles the item lists we asked for.

```
// Get a MenuHandler instance that handles an ItemList named "main"
Menu::handler('main');
```

When we call a method on this menu handler, it will simply forward the call to all the item lists that it handles. In order to find out what we can do now that we have a handler, we need to take a look at the methods on the ItemList class.

The *ItemList* class has a method called **add** that you are probably going to use a lot. It adds an *Item* of type "link" to the *ItemList*.

```
Menu::handler('main')->add('home', 'Homepage');

/* The add method takes these arguments
  $url  string  The URL to another page
  $title  string  The visible string on the link
  $children (default = null)  ItemList  (optional) The children of this page
  $link_attributes (default = array())  array (optional) HTML attributes for the  element
  $item_attributes (default = array())  array (optional) HTML attributes for the list element (usually )
  $item_element (default = 'li')  string  (optional) The type of the list element
*/
```

Let's take a look at the **raw** method, for adding "anything" to the list.

```
Menu::handler('main')->raw('');

/* The raw method takes these arguments
  $html string  The contents of the item
  $children (default = null)  ItemList  (optional) The children of this item
  $item_attributes (default = array())  array (optional) HTML attributes for the list element (usually )
  $item_element (default = 'li')  string  (optional) The type of the list element
*/
```

Great! Now that we have learned how to add items to an item list, let's have a look at how we add children to a item. Every item can have children, the children object is just another *ItemList*. As we have seen before, we can create item lists via the **handler** method, but this method returns a *MenuHandler*, making it unusable for item children. So what do we use? the **items** method returns a fresh *ItemList* object. Let's have a look.

```
Menu::handler('main')
    ->add('home', 'Homepage', Menu::items()
        ->add('sub-of-home', 'Sub of homepage'));

/* The items method takes these arguments
  $name (default = null)  string  (optional) The name (=identifier) of this ItemList
  $attributes (default = array()) array (optional) HTML attributes for the ItemList element (usually )
  $element (default = 'ul') string  (optional) The type of the ItemList element
*/
```

So now we know how to build menus, add items and items with children. Let's find out how to display the menus. The MenuHandler and *ItemList* classes implement the "\_\_toString" method, that calls the **render** method. This means you can simply echo the MenuHandler or *ItemList* object. Here is an example to make things more clear.

```
echo Menu::handler('main');

// Is the same as

echo Menu::handler('main')->render();
```

Now that we have the basics under control, we are going to explore some other cool features this package provides.

Class diagram
=============

[](#class-diagram)

[![Class diagram](https://camo.githubusercontent.com/988a515acdb94260da07de8f047d502c6b96a01fac237105d9ab3f848f908472/687474703a2f2f7261776769746875622e636f6d2f76657370616b6f656e2f6d656e752f6d61737465722f6d656e752d636c6173732d6469616772616d2e737667)](http://rawgithub.com/vespakoen/menu/master/menu-class-diagram.svg)

Some last words
===============

[](#some-last-words)

Thanks for following along and using this package. Special thanks to @Anahkiasen for refactoring this package and boosting new life into it!

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity46

Moderate usage in the ecosystem

Community34

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~104 days

Recently: every ~391 days

Total

24

Last Release

2155d ago

Major Versions

2.0.15 → 3.02015-02-08

2.0.16 → 3.0.52020-06-24

PHP version history (2 changes)2.0.0PHP &gt;=5.3.0

3.0PHP &gt;=5.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/beb3e5e89606ac13954df233e7b6465cf7eba8c01c9c1c64b30ac9fbc020e312?d=identicon)[Vespakoen](/maintainers/Vespakoen)

---

Top Contributors

[![Anahkiasen](https://avatars.githubusercontent.com/u/1321596?v=4)](https://github.com/Anahkiasen "Anahkiasen (141 commits)")[![vespakoen](https://avatars.githubusercontent.com/u/876117?v=4)](https://github.com/vespakoen "vespakoen (132 commits)")[![memco](https://avatars.githubusercontent.com/u/1486098?v=4)](https://github.com/memco "memco (20 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (5 commits)")[![nticaric](https://avatars.githubusercontent.com/u/824840?v=4)](https://github.com/nticaric "nticaric (3 commits)")[![yuri-moens](https://avatars.githubusercontent.com/u/1128153?v=4)](https://github.com/yuri-moens "yuri-moens (2 commits)")[![nostalgie](https://avatars.githubusercontent.com/u/2854494?v=4)](https://github.com/nostalgie "nostalgie (1 commits)")[![msurguy](https://avatars.githubusercontent.com/u/585833?v=4)](https://github.com/msurguy "msurguy (1 commits)")[![rendom](https://avatars.githubusercontent.com/u/1078548?v=4)](https://github.com/rendom "rendom (1 commits)")[![rojtjo](https://avatars.githubusercontent.com/u/1123887?v=4)](https://github.com/rojtjo "rojtjo (1 commits)")[![tobiasneidig](https://avatars.githubusercontent.com/u/8065624?v=4)](https://github.com/tobiasneidig "tobiasneidig (1 commits)")[![markcameron](https://avatars.githubusercontent.com/u/1106894?v=4)](https://github.com/markcameron "markcameron (1 commits)")[![carbontwelve](https://avatars.githubusercontent.com/u/464699?v=4)](https://github.com/carbontwelve "carbontwelve (1 commits)")

---

Tags

laravelmenularavel 5

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/vespakoen-menu/health.svg)

```
[![Health](https://phpackages.com/badges/vespakoen-menu/health.svg)](https://phpackages.com/packages/vespakoen-menu)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3274.9M308](/packages/psalm-plugin-laravel)[unisharp/laravel-filemanager

A file upload/editor intended for use with Laravel 5 to 10 and CKEditor / TinyMCE

2.2k3.3M74](/packages/unisharp-laravel-filemanager)[watson/active

Laravel helper for recognising the current route, controller and action

3253.6M14](/packages/watson-active)[anahkiasen/former

A powerful form builder

1.4k1.4M14](/packages/anahkiasen-former)[laragear/preload

Effortlessly make a Preload script for your Laravel application.

119363.5k](/packages/laragear-preload)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
