Updated (August 2019): Thanks for helping us to fix typo issues of this tutorial.
Overview
Today I will cover one of the most wanted & useful topics "Nested Menu in Laravel"
In this article we will demonstrates usage of Nestable plugin jQuery plugin to provide the user with nice menu ordering experience without a page refresh.
This article is unique in web, at least I couldn’t find any similar article for nestable menus in laravel or even close to this.
What we need
Creating the menu controller in app/controllers/MenuController.php and the menu model is in app/models/Menu.php
A note on the data structure for the menu
The important columns of the "menus" table are:
id
parent_id
order
With these 3 fields we can build nested menus as many levels deep as you want. The Nestable plugin helps modify the values of these fields for the appropriate rows of data.
Use of recursion
The hard part that took me a long time to build is a very small function inside of app/models/Menu.php:
This function uses recursion to display the menu to the user even if the menu is many many levels deep. This function alone can save you a bunch of time.
Let’s code
Step 1
Make Menu model and migration for it. Open your terminal and type command below
With this artisan command we tell laravel to make model named Menu in App folder and migration file for our schema in database/migrations folder.
Step 2
Make Menu controller. Open your terminal and type command below
With this artisan command we tell laravel to make controller named MenuController in App\Http\Controllers folder.
Step 3
- Make schema
Open your migration file that you created in step 1 and add following codes,
remember columns id , parent_id & order are important to us rest of them are optional.
Now save the file and close it.
- Prepare model
- Prepare model
Open your Menu model and add following codes,
Now save add close it.
- Migrate your schema with following command
Step 4
Now we have everything ready let’s take care of our MenuController and then make our views.
Open your MenuController which you create in step 2 and add following code.
Step 5
Adding routes
add this routes to your web.php file
Step 6
Creating views
In views folder create new folder name it admin and inside that create new folder name it menus, we will make all this views in menus folder.
Create index.blade.php add this codes: (remember change the design as your admin panel style goes)
Create edit.blade.php and add following code.
That's all you need to make nestable menu in your laravel application, hope you find this article useful to you. If so, don't forget to hit love emoji below this post.
Be the first to leave a comment.