Laravel 7.x Hierarchical Treeview Category Example

I was working on application where I had to create hierarchical relationship for a Model entity and also figure out a way to display it in HTML. 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 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. 

We also see how we can create dynamic menu and submenu in laravel, 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 7. 

Now i am going to show you how we can create laravel treeview for multi level data. In this laravel tree example tutorial i won't use any packages. I will show you it using eloquent self relationship with category model. let's start. You can see from below image what we are going to create. 

Preview

laravel-treeview-category-example

Now let's see how we can create laravel mega menu. 

Step 1: Install Laravel 6 Application

In first step to create category management in laravel , 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: Create Category  Model

Let’s set up a Category model along with the migration file

php artisan make:model Category -m

Create Hierarchical Relationship in Laravel

For this article we will consider an simplest example of multi-level dataset i.e. category and subcategory.Here is how the category-subcategory relationship looks like

A category can have multiple subcategory, a subcategory can also have multiple subcategory and so on…

Let’s consider you have a Category model in your application and you are looking to have a relationship with the self table so that you can store subcategories as well.

Let’s now go ahead and modify the migration file to add the required columns.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->unsignedInteger('parent_id')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

 

After create "categories" table you should create Category model for categories, so first create file in this path app/Category.php and put bellow content in item.php file:

app/Category.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $guarded = [];

    public function subcategory(){

        return $this->hasMany('App\Category', 'parent_id');

    }
}

 

Read the relationship as : A Category and have many Category (Subcategory) and is associated with parent_id foreign key. This is a relationship with self-table.

 

Step 3: Create Route

In this is step we need to create two route one for render treeview and second for add new category file. so open your routes/web.php file and add following route.

routes/web.php

Route::get('/category','[email protected]')->name('category');

 

Step 4: Create Controller

In this point, now we should create new controller call CategoryController in this path app/Http/Controllers/CategoryController.php. In this controller we will manage route method, i added two method in this controller as listed bellow:

app/Http/Controllers/CategoryController.php


namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CategoryController extends Controller
{

    public function index()
    {
        $parentCategories = \App\Category::where('parent_id',0)->get();

        return view('product.categoryTreeview', compact('parentCategories'));
    }
}

 

Step 5: Create View

In this step, we have to create total two blade file as listed bellow:

1. categoryTreeview.blade.php

2. manageChild.blade.php

This both blade file will help to render category tree structure, so let's create both file view file and put bellow code.

resources/views/product/categoryTreeview.blade.php

@foreach($parentCategories as $category)
 
  {{$category->name}}

  @if(count($category->subcategory))
    @include('product.subCategoryList',['subcategories' => $category->subcategory])
  @endif
 
@endforeach

 

resources/views/product/subCategoryList.blade.php

 

We have made use of recursion to call this view file again and again until the parent does have any further child data. That’s it. Above image is how the output will be look like. I have used below data to insert manually. You can insert it and check it. 

laravel-treeview-example

 

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

 

Ok, now you are ready to run and check your application. I hope it can help you...