Laravel 7.x Category Treeview | How to Display Hierarchical Data

I was working on application where I had to create hierarchical relationship to show multi level subcategories in laravel. In this tutorial we will see how we can create laravel mega menu.

I decided to write an article on this as I came across similar questions over the internet and the process which I have gone through might help someone looking for similar solution.

In this tutorial i simple create "categories" table and manage end level of parents and child category with nested tree view structure in Laravel application. I use jquery for make tree view layout and child relationship with category model for hierarchical data. I also add form for create new category in tree view.

We also see how we can create dynamic menu and submenu in larave, that mean you can also create mega menu in laravel using this system. Multi level subcategories system in laravel. You will learn how to display category and subcategory in laravel 6. 

If you are new in laravel then also you can do it simple and also simply customize it because this tutorial from scratch. You can simple following bellow step, you will get category tree view in your application as bellow preview.

 

Read also : Laravel 6 Ajax Form Submit With jQuery Validation

 

laravel-treeview-example

 

Step 1: Install Laravel  Application

 

In first step, if you haven't laravel 6 application setup then we have to get fresh laravel 6 application. So run bellow command and get clean fresh laravel 6 application.

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

 

Step 2: Install laravel-nestedset composer package.

You can find the official Github Library here. We need to type the following command to pull it through composer.

composer require kalnoy/nestedset

 

Step 3: Create a model and database migration

In the terminal, type the following command.

php artisan make:model Shop -m

 

So, it will generate the model as well as migration file. 

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Kalnoy\Nestedset\NestedSet;

class CreateShopsTable extends Migration
{
   
    public function up()
    {
        Schema::create('shops', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('category_name');
            NestedSet::columns($table);
            $table->timestamps();
        });
    }

    
    public function down()
    {
        Schema::dropIfExists('shops');
    }
}

 

So, this shops table contain the category_name and Nested Set columns. Now, migrate the table using the following command.

php artisan migrate

 

We can see that in our shops’ table there are three columns, which is related to Nested Set. After migrating we will get such kind of look of our category table.

laravel-treeview

 

Step 4: Seed the Database.

So first, create the Seeder file using the following command.

php artisan make:seeder ShopTableSeeder

 

Okay, now write the following code inside ShopTableSeeder.php file.

database/seeds/ShopTableSeeder.php

use Illuminate\Database\Seeder;

class ShopTableSeeder extends Seeder
{
    public function run()
    {
        $shops = [
            [
                'category_name' => 'Books',
                    'children' => [
                        [    
                            'category_name' => 'Comic Book',
                            'children' => [
                                    ['category_name' => 'Marvel Comic Book'],
                                    ['category_name' => 'DC Comic Book'],
                                    ['category_name' => 'Action comics'],
                            ],
                        ],
                        [    
                            'category_name' => 'Textbooks',
                                'children' => [
                                    ['category_name' => 'Business'],
                                    ['category_name' => 'Finance'],
                                    ['category_name' => 'Computer Science'],
                            ],
                        ],
                    ],
                ],
                [
                    'category_name' => 'Electronics',
                        'children' => [
                        [
                            'category_name' => 'TV',
                            'children' => [
                                ['category_name' => 'LED'],
                                ['category_name' => 'Blu-ray'],
                            ],
                        ],
                        [
                            'category_name' => 'Mobile',
                            'children' => [
                                ['category_name' => 'Samsung'],
                                ['category_name' => 'iPhone'],
                                ['category_name' => 'Xiomi'],
                            ],
                        ],
                    ],
                ],
        ];
        foreach($shops as $shop)
        {
            \App\Shop::create($shop);
        }
    }
}

 

Now, go to the DatabaseTableSeeder.php file and add the following code.

database/seeds/DatabaseTableSeeder.php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        $this->call(ShopTableSeeder::class);
    }
}

 

Open your Shop model and paste this following code.

app/Shop.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Kalnoy\Nestedset\NodeTrait;

class Shop extends Model
{   
    use NodeTrait;
    
    protected $guarded = [];
}

 

Go to the terminal and seed using the following command.

php artisan db:seed

 

Step 5: Display the Hierarchical data into the View.

Now, we have got the data, we just need to pass that data into the View and display the data according to a parent-child relationship. 

routes/web.php

Route::get('/shop', function () {
    
    $product = \App\Shop::get()->toTree();

    return view('welcome', compact('product'));
 
})->name('shop');

 

Now, finally create one file inside views folder called welcome.blade.php and paste those following code.

 

Read also :  Vue Laravel CRUD Example With Vue Router & Sweet Alert

 

We can use this hierarchy to build the Mega menu for the Shopping Categories. So this is the basic example of laravel treeview structure. Hope it will help you.