Laravel 5.2 Dynamic Menu via MiddleWare.
In the following tutorial, I will guide you how to build a dynamic menu based on database table, so that the admin user can re-arrange it or create new one based on business requirement without coding.
1-Build a database table to hold the menu tree structure. The table will hold the menu item id, menu parent to keep the tree structure, the order to build item sibling and put the menu item in the correct position, and menu slug which used to build the item URL.
2-Install third party tree library which will be used to load and build menu tree from the menu database table, and will be used for tree traverse. For this tutorial we will use “https://github.com/nicmart/Tree”. Please follow the instructions to install it.
3- Add Middleware Class to handle all requests before sending it to Controllers, by create class in app/Http/Middleware/buildMenu.php
Add the implementation to buildMenuTree method which will be used to build the menu tree and store it in the session variable to be used in each web page view. For production version we will add condition to check if the session contains the menu variable to re-use it for performance enhancement.
4-Building helper functions for front-end menu building and converting it to HTML/CSS for views. It will be used for tree traversal as well to build the requirement.
5-Building header partial to be used in the Blade view and display dynamic menu bar. Header partial will call our helper functions to generate the required HTML/CSS.