Wabbitseason
Wabbitseason

Reputation: 5691

How to structure code in Laravel for user role based menu?

After a user logs in to an app I am developing, based on their role they need to be presented with a different set of menu items.

I have created a filter called "menu" in which I assemble the menu items. I have this in my routes.php to run my filter before everything:

Route::group(array('before' = 'auth|menu'), function()...

At the end of my menu filter I have this to make the menu class accessible in every view:

View::share('menu', $menu);

For actually building the menu I am using the Laravel Menu bundle, but I haven't yet found the best way to dynamically set the "active" flag of a menu item from my controllers.

The Menu bundle examines the URL to set the active flag (which does not work for me as it seems to be comparing the pathname with URI::current(), only the latter returns the full URL with domain, port and everything, so it never matches) but I would rather like to somehow access the $menu class from within my controllers so I could directly modify it.

How should I do this? Is this situation when one uses a Registry (a.k.a. glorified global variable)?

Upvotes: 2

Views: 2023

Answers (1)

Raftalks
Raftalks

Reputation: 2037

Will give u the basic idea and you will be ready to move ahead. Use the IoC container to instantiate the menu object as singleton and then access it from your controller or views. Another way to inject menu is using the View Composer. You can look deep into Laravel docs and source codes.

Upvotes: 3

Related Questions