Laravel 9 Category Subcategory Example Step By Step
Hello Artisan,
In this laravel 9 dynamic tree view laravel tutorial, I will show you step by step way of how to create dynamic category and subcategory in laravel without using any packages. I will create a pure dynamic laravel multi level category subcategory example.
I was working on an application where I had to create a hierarchical relationship for a Model entity and also figure out a way to display it in HTML. In this tutorial, I simply create a "categories" table and manage the end level of parents and child categories with a nested tree view structure in Laravel application.
We also see how we can create dynamic menu and submenu in laravel 9 using this category subcategory tree, which means you can also create a mega menu in laravel 9 using this system. You will aslo learn how to display category and subcategory in laravel 9.
In this multi level subcategories system in laravel 9 example. I will put a parent_id
and using this, I will create a self-relationship with the Category
model. Let's start:
Preview
Now let's see how we can create laravel mega menu.
Step 1: Install Laravel 9 Application
In the first step to creating category management in laravel , if you haven't laravel 9 application setup then we have to get a fresh laravel 9 application. So run the below command and get a clean fresh laravel 9 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 the simplest example of a 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 creating the categories
table you should create a Category model for categories, so first create a file in this path app/Category.php and put the below content in the Category.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
a foreign key. This is a relationship with self-table.
Step 3: Create Route
In this is a step we need to create two routes one for rendering treeview and the second for adding a new category file. so open your routes/web.php file and add the following route.
routes/web.php
Route::get('/category','ShopController@index')->name('category');
Step 4: Create Controller
At this point, now we should create a new controller called CategoryController in this path app/Http/Controllers/CategoryController.php. In this controller we will manage the route method, I added two methods in this controller as listed below:
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 a total two-blade file as listed below:
- categoryTreeview.blade.php
- manageChild.blade.php
Both blade files will help to render category tree structure, so let's create both file view files 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
Now update this to complete how to show subcategory under category in laravel 9 application.
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. The above image is what the output will look like. I have used the below data to insert manually. You can insert it and check it.
Read also : Laravel 9 Category Treeview | How to Display Hierarchical Data
Now category subcategory data are ready using laravel parent child category relationship. I hope it can help you.