Skip to content
niknetniko edited this page Mar 5, 2016 · 4 revisions

Caffeinated Menus comes with similar filter() functionality that Laravel Collections provides. With it, you could easily filter through your menu items for cases where you may need to check for permissions (or anything, really).

Filtering works exactly the same way as would the Laravel Collection's filter() method.

Define a callback closure, pass through your menu items, perform your filtering, and simply return a boolean based on if the item should be filtered out or kept (false or true, respectively).

Here's a simple example using the Caffeinated Shinobi package to check if the user has the correct permissions to access the given links (it's a silly example, but just roll with it):

Menu::make('example', function(Builder $menu) {
    $menu->add('Home', '/')->data('permissions', ['view_home_page']);
    $menu->add('About', '/about')->data('permissions', ['view_about_page']);
    $menu->add('Admin', '/admin')->data('permissions', ['access_admin']);
})->filter(function($item) {
    return Auth::check() && Auth::user()->canAtLeast($item->data('permissions')) ?: false;
});
Clone this wiki locally