How to create a multilevel category and subcategory in Laravel – Part1?

/
/
/
2050 Views

In this tutorial of 91 TechSquare, we will learn how to create a multilevel category and subcategory in Laravel. We will use a single table to create a multilevel category and subcategory in Laravel.

We will implement the functionality to create a multilevel category and subcategory in Laravel with simple steps. Please follow the below steps to accomplish this.

create multilevel category and subcategory in Laravel
create multilevel category and subcategory in Laravel

1. Install Laravel Project:

If you have already installed a Laravel project then skip this step otherwise you the below command in your terminal to install a new Laravel project.

composer create-project laravel/laravel category-subcategory-project

Then go inside the Laravel project directory

cd category-subcategory-project

2. Make database setup

Create a database and setup it in .env file

3. Create Model and migration

Run the below command to create model and migration table:

php artisan make:model Category -m

Paste the following code in migration file. Migration file will be available in database/migrations/

<?php

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

class CreateCategoriesTable extends Migration
{
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug')->unique();
            $table->integer('parent_id')->nullable();
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

Paste the following code in model file. Model file will be available in app/Models/Category.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;
    protected $fillable = ['name', 'slug', 'parent_id'];

    public function subcategory()
    {
        return $this->hasMany(\App\Models\Category::class, 'parent_id');
    }

    public function parent()
    {
        return $this->belongsTo(\App\Models\Category::class, 'parent_id');
    }
}

In the above code, we made the relationship between parent_id and model itself. It will need to show the list of categories in the parent category dropdown.

4. Migrate the database:

Run the below migration command to create category table inside database.

php artisan migrate

5. Create Routes:

In this step, we will create a route for insert categories into our database. This route will handle the request to create a multilevel category and subcategory.

Route::any('category/create', [CategoryController::class, 'createCategory'])->name('createCategory');

We used a single route to perform all types of requests such as to get requests or post requests. You can create according to your need as well. CategoryController already includes at the top of the route file so do not be confused.

6. Create Controller:

In this step, we will create a controller and method to insert data and render the view file. Run the following command to create a controller:

php artisan make:controller CategoryController

Use the following code into your controller for createCategory route.

<?php

namespace App\Http\Controllers;

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

class CategoryController extends Controller
{
    public function createCategory(Request $request)
    {
        $categories = Category::where('parent_id', null)->orderby('name', 'asc')->get();
        if($request->method()=='GET')
        {
            return view('create-category', compact('categories'));
        }
        if($request->method()=='POST')
        {
            $validator = $request->validate([
                'name'      => 'required',
                'slug'      => 'required|unique:categories',
                'parent_id' => 'nullable|numeric'
            ]);

            Category::create([
                'name' => $request->name,
                'slug' => $request->slug,
                'parent_id' =>$request->parent_id
            ]);

            return redirect()->back()->with('success', 'Category has been created successfully.');
        }
    }
}

7. Create View for createCategory Route:

To create a multilevel category and subcategory in this step we will create view files. Here we will create two files for creating a view, first one is to create, and the second one is to display choose parent category list in hierarchical order:

Create two blade files as following:

  • views/create-category.blade.php
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<section class="content" style="padding:20px 30%;">
    <div class="row">
        <div class="col-md-12">
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">Create Category</h3>
                </div>
                
                <form role="form" method="post">
                    {{csrf_field()}}
                    <div class="box-body">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="form-group">
                                    <label>Category name*</label>
                                    <input type="text" name="name" class="form-control" placeholder="Category name" value="{{old('name')}}" required />
                                </div>
                            </div>

                            <div class="col-sm-12">
                                <div class="form-group">
                                    <label>Category Slug*</label>
                                    <input type="text" name="slug" class="form-control" placeholder="Category name" value="{{old('slug')}}" required />
                                </div>
                            </div>

                            <div class="col-sm-12">
                                <div class="form-group">
                                    <label>Select parent category*</label>
                                    <select type="text" name="parent_id" class="form-control">
                                        <option value="">None</option>
                                        @if($categories)
                                            @foreach($categories as $category)
                                                <?php $dash=''; ?>
                                                <option value="{{$category->id}}">{{$category->name}}</option>
                                                @if(count($category->subcategory))
                                                    @include('subCategoryList-option',['subcategories' => $category->subcategory])
                                                @endif
                                            @endforeach
                                        @endif
                                    </select>
                                </div>
                            </div>

                        </div>
                    </div>
                    <div class="box-footer">
                        <button type="submit" class="btn btn-primary">Create</button>

                    </div>
                </form>

                @if ($errors->any())
                    <div>
                        @foreach ($errors->all() as $error)
                            <li class="alert alert-danger">{{ $error }}</li>
                        @endforeach
                    </div>
                @endif

                @if(\Session::has('error'))
                    <div>
                        <li class="alert alert-danger">{!! \Session::get('error') !!}</li>
                    </div>
                @endif

                @if(\Session::has('success'))
                    <div>
                        <li class="alert alert-success">{!! \Session::get('success') !!}</li>
                    </div>
                @endif
            </div>
        </div>
    </div>
</section>

Create another view file to show parent categories to choose in hierarchical order

  • views/subcategoryList-option.blade.php
<?php $dash.='-- '; ?>
@foreach($subcategories as $subcategory)
    <option value="{{$subcategory->id}}">{{$dash}}{{$subcategory->name}}</option>
    @if(count($subcategory->subcategory))
        @include('subCategoryList-option',['subcategories' => $subcategory->subcategory])
    @endif
@endforeach

That’s it, now you can run the project by command php artisan serve, and visit the below route to create a multilevel category and subcategory in Laravel:

http://127.0.0.1:8000/category/create

Hopefully, You got an idea about how to create a multilevel category and subcategory using a single table. If you want to know more about this then click on how to display category and subcategory in Laravel?

5 Comments

  1. I’m confused why using include for the views? Can you explain? Because when i run the code it was showing error

Leave a Comment

Your email address will not be published. Required fields are marked *

This div height required for enabling the sticky sidebar