caffeinated / menus

:pushpin: Menu generator package for the Laravel framework
https://caffeinatedpackages.com
132 stars 59 forks source link

Add ability to filter through menu items #26

Closed AlexRegenbogen closed 9 years ago

AlexRegenbogen commented 9 years ago

I'm currently trying to have the builder check if each item will give access before it's added to the tree. (ACL-based, defined on the routes)

Basically what I'm trying to do, is filter out items that are not accessible to the user. (If a root item is not allowed via ACL, then all underlying items are also prohibited)

Initially I was looking into overriding Builder::add() to match the given URL to the routes, and then checking the route if it matches for access. But If an item is not allowed, I'm not able to return nothing from add().

Am I looking into the wrong direction? ;-)

kaidesu commented 9 years ago

I should add a way to filter menu items, which would cover this use case.

In the mean time, you're able to assign any additional meta data you may have to your menu items through the data() method (documentation page here). You could make use of that to filter items based on permissions somewhere in your code before the menu is passed to your view.

kaidesu commented 9 years ago

Just pushed v1.0.3, which has the ability to filter menu items. Here's a simple usage example:

Menu::make('test', function($menu) {
    $menu->add('Google', 'http://google.com')->data('permissions', ['view_google']);
})->filter(function($item) {
    dd($item->data('permissions'));

    // Simply check if your users can perform the defined permissions, and return a boolean.
    // If you're using the Caffeinated Shinobi package, the usage would simply be:
    //
    // return Auth::user()->can($item->data('permissions'));
});
mackhankins commented 9 years ago

Could this work with middleware?

kaidesu commented 9 years ago

To be honest, I don't know. Haven't tried or messed around with creating middleware myself.

If it helps any, the filter() method here literally forwards to the Laravel Collection filter() method. That may help you Google-fu for an answer~

mackhankins commented 9 years ago

Okay, that actually helps. I'm using Entrust, but to be fair all I need is simple permissions which might send me over to Shinobi. I might be better off moving my menu to a custom composer that I can send permissions to or something like that.

Custom Middleware https://laracasts.com/discuss/channels/general-discussion/check-if-user-has-admin-role-1