Search

Step-by-Step Guide to Creating a Multi-Level Dynamic Menu in Laravel Using Treeview

  • Share this:
Step-by-Step Guide to Creating a Multi-Level Dynamic Menu in Laravel Using Treeview

Creating a multi-level dynamic menu in Laravel using Treeview can be a bit daunting for beginners. However, with the right guidance, anyone can accomplish this task. In this blog, I'll show you how to create a multi-level dynamic menu in Laravel using Treeview and also how to make it SEO friendly.


What is Treeview?

Treeview is a plugin that provides a treeview structure for HTML lists. It is a lightweight jQuery plugin that allows you to convert nested unordered lists into an expandable and collapsible tree view.

Step 2: Create a Database


Next, create a database in MySQL or any other database management system of your choice.

Step 3: Create a New Laravel Project

To create a new Laravel project, open your command prompt and enter the following command:

composer create-project --prefer-dist laravel/laravel project-name

 


Step 4: Create a Model and Migration

To create a model and migration for the menu, run the following command in your command prompt:
php artisan make:model Menu -m

Step 5: Modify the Migration File

Open the migration file that was created in the previous step and modify it to create the menu table. The menu table should have the following fields:

        Schema::create('menus', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('parent_id')->nullable();
            $table->integer('order')->default(0);
            $table->timestamps();
      });

Step 6: Run the Migration

Run the migration to create the menu table in the database by running the following command:

php artisan migrate

Step 7: Seed the Database

To seed the database with some sample data, create a seeder by running the following command:
php artisan make:seeder MenuSeeder

Open the MenuSeeder file and add the following code to create some sample menu items:

    <?php
   
    use App\Models\Menu; // import the Menu model
    use Illuminate\Database\Seeder;
   
    class MenuSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {
            // Define an array of menu items
            $items = [
                ['name' => 'Home', 'order' => 1],
                ['name' => 'About Us', 'order' => 2],
                ['name' => 'Services', 'order' => 3],
                ['name' => 'Products', 'order' => 4],
                ['name' => 'Contact Us', 'order' => 5],
                ['name' => 'Services 1', 'parent_id' => 3, 'order' => 1],
                ['name' => 'Services 2', 'parent_id' => 3, 'order' => 2],
                ['name' => 'Services 3', 'parent_id' => 3, 'order' => 3],
                ['name' => 'Products 1', 'parent_id' => 4, 'order' => 1],
                ['name' => 'Products 2', 'parent_id' => 4, 'order' => 2],
            ];
   
            // Loop through each menu item and create a new database record using the Menu model
            foreach ($items as $item) {
                // The Menu model's create() method is used to create a new database record
                // The $item array is used to populate the fields of the new record
                Menu::create($item);
            }
        }
    }

This will create the sample menu items in the database.

 

Step 8: Create a Controller

To create a controller for the menu, run the following command:
php artisan make:controller MenuController

Open the MenuController file and add the following code:

<?php

namespace App\Http\Controllers;

use App\Models\Menu;
use Illuminate\Http\Request;

class MenuController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $menus = Menu::where('parent_id', '=', null)->orderBy('order')->get();
        return view('menu.index', compact('menus'));
    }
}

This code retrieves all the menu items that have no parent and orders them by the "order" field.

 

Step 9: Create a View

To create a view for the menu, create a new file called "index.blade.php" in the "resources/views/menu" directory and add the following code:

    <ul>
        @foreach ($menus as $menu)
            <li>
                {{ $menu->name }}
                @if (count($menu->children))
                    @include('menu.submenu', ['menus' => $menu->children])
                @endif
            </li>
        @endforeach
    </ul>

 

This code loops through all the menu items that have no parent and displays their names. If a menu item has children, it includes another view called "submenu.blade.php".

Step 10: Create a Submenu View

Create a new file called "submenu.blade.php" in the "resources/views/menu" directory and add the following code:

    <ul>
        @foreach ($menus as $menu)
            <li>
                {{ $menu->name }}
                @if (count($menu->children))
                    @include('menu.submenu', ['menus' => $menu->children])
                @endif
            </li>
        @endforeach
    </ul>

 

This code is similar to the previous code, but it displays the children of the menu items.

Step 11: Update the Routes

 

Open the "routes/web.php" file and add the following code:

Route::get('/', [MenuController::class,'index']);

 

Step 12: Test the Application

 

Run the following command to start the Laravel development server:

php artisan serve

 

Open your web browser and navigate to "http://localhost:8000". You should see the menu displayed on the page.


Jahangir Alam

Jahangir Alam

I'm a full-stack website developer with a wealth of experience in creating beautiful and functional websites. I have a strong foundation in web development and am well-versed in a variety of programming languages, including HTML, CSS, JavaScript, and PHP.
With over 3 years of experience in the industry, I have worked on a wide range of projects, from small startup websites to large enterprise-level applications. He has a proven track record of delivering high-quality results, on time and within budget.
I am comfortable working with various web development frameworks such as React, Angular, and Vue.js. He has strong knowledge of the latest web development trends and best practices, which he uses to create responsive and user-friendly websites.