Laravel

How to Create a Multilevel Category and Subcategory in Laravel with Bootstrap UI

Laravel

How to Create a Multilevel Category and Subcategory in Laravel with Bootstrap UI

Hey there, fellow developers! 🤗 In this tutorial, we'll walk through the process of creating a multilevel category and subcategory system in Laravel using the powerful Eloquent ORM. To make it visually appealing, we'll integrate Bootstrap UI for the frontend. Let's dive in and build this feature step by step!

Step 1: Set Up a New Laravel Project 🛠️ Make sure you have Laravel installed on your system. If not, visit the official Laravel website and follow their installation guide to create a new project.

Step 2: Set Up the Database 🗄️ Create a new MySQL database for your project, and update the database credentials in the .env file of your Laravel project.

Step 3: Create the Category Model and Migration 📁 Generate a new model and migration for the categories table using the following command:

php artisan make:model Category -m

In the generated migration file, define the necessary columns for the categories table, such as id, name, and parent_id.

Step 4: Run the Migration 🚀 Execute the migration to create the categories table in the database:

php artisan migrate

Step 5: Define the Category Relationships 🤝 In the Category model, define the relationships for the subcategories:

class Category extends Model
{
    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

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

Step 6: Create the Category Controller 🌐 Generate a new controller to handle category-related actions:

use App\Models\Category;

public function index()
{
    $categories = Category::whereNull('parent_id')->with('children')->get();
    return view('categories', compact('categories'));
}

public function store(Request $request)
{
    Category::create([
        'name' => $request->input('name'),
        'parent_id' => $request->input('parent_id'),
    ]);

    return redirect()->route('categories.index')->with('success', 'Category added successfully!');
}

Step 7: Set Up the Category Routes 🚦 In your routes/web.php, define the routes for managing categories. For instance:

Route::get('/categories', 'CategoryController@index')->name('categories.index');
Route::post('/categories', 'CategoryController@store')->name('categories.store');

Step 8: Create the Blade Views 🎨 Now, create the necessary Blade views for managing categories. We'll create categories.blade.php to display the category tree and create.blade.php for adding new categories. Utilize Bootstrap to style your UI for an elegant appearance.

Example categories.blade.php:

@extends('layout')

@section('content')
    <div class="container mt-5">
        <h2>Categories</h2>
        <ul>
            @foreach ($categories as $category)
                <li>
                    {{ $category->name }}
                    @if ($category->children)
                        @include('partials.subcategories', ['categories' => $category->children])
                    @endif
                </li>
            @endforeach
        </ul>
    </div>
@endsection

And the subcategories.blade.php file:

<ul>
    @foreach($subcategories as $subcategory)
        <li>
            {{ $subcategory->name }}
            @if(count($subcategory->subcategories) > 0)
                @include('subcategories', ['subcategories' => $subcategory->subcategories])
            @endif
        </li>
    @endforeach
</ul>

Example create.blade.php:

@extends('layout')

@section('content')
    <div class="container mt-5">
        <h2>Add New Category</h2>
        <form action="{{ route('categories.store') }}" method="post">
            @csrf
            <div class="form-group">
                <label for="name">Category Name</label>
                <input type="text" name="name" class="form-control">
            </div>
            <div class="form-group">
                <label for="parent_id">Parent Category</label>
                <select name="parent_id" class="form-control">
                    <option value="">No Parent</option>
                    @foreach ($categories as $category)
                        <option value="{{ $category->id }}">{{ $category->name }}</option>
                    @endforeach
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Add Category</button>
        </form>
    </div>
@endsection

Step 9: Test Your Multilevel Category System! ✔️ Now, run your Laravel development server using php artisan serve and visit http://localhost:8000/categories in your browser. You should see the category tree structure, and you can add new categories using the "Add New Category" form.

Congratulations! 🎉 You've successfully implemented a multilevel category and subcategory system in Laravel with Bootstrap UI.