Laravel

Implementing a Multi-level Parent-Child Relationship for Product Categories in Laravel

In modern web applications, organizing products or content into categories is a common requirement. When these categories need to have a hierarchical structure, such as subcategories within main categories, a multi-level parent-child relationship becomes essential. Laravel, a popular PHP framework, provides powerful tools for implementing such relationships in a clean and efficient manner. In this blog post, we'll walk you through the process of creating a multi-level parent-child relationship for product categories in Laravel.

Prerequisites:
Before we dive into the implementation, make sure you have the following prerequisites in place:

  • 1. A Laravel project up and running.
  • 2. Basic understanding of Laravel migrations, models, and Blade templating.

 

Step 1: Creating the Category Model and Migration:

We'll start by creating a Category model along with a migration that defines the categories table structure. Run the following Artisan command to generate the model and migration:

php artisan make:model Category -m

In the generated migration file, define the table columns required for the category hierarchy:

Schema::create('categories', function (Blueprint $table) {
   $table->id();
   $table->string('name');
   $table->unsignedBigInteger('parent_id')->nullable();
   $table->timestamps();
});

Run the migration to create the categories table:

php artisan migrate

Step 2: Defining the Category Model Relationships:

In the Category model (`Category.php`), set up the parent-child relationships using Laravel's Eloquent ORM:

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

Step 3: Creating Recursive Category Dropdown Helper:

To generate a hierarchical dropdown of categories in Blade views, we'll create a recursive helper function. Add the following code to a helper file or directly in the `Category` model:

public function cat_list($parent_id = 0, $space = '', $selected_id = [0], $disabled = 0)
{
 $categories_all = Category::all();
 echo $this->cat_list_parent($parent_id, $space, $selected_id, $disabled, $categories_all);
}
public function cat_list_parent($parent_id, $space, $selected_id, $disabled, $categories_all)
{
 $categories = $categories_all->filter(function ($item) use ($parent_id) {
     return $item->parent_id == $parent_id;
 });
 $count = count($categories);
 if ($parent_id == 0) {
     $space = '';
 } else {
     $space .= "¦––";
 }
 if ($count > 0) {
     foreach ($categories as $category) {
         $data = $category->id;
         $selected = "";
         if (in_array($data, $selected_id)) {
             $selected = "selected";
         }
         $disabled_at = "";
         if ($category->id == $disabled) {
             $disabled_at = "disabled";
         }
         echo "<option " . $selected . " url='".route('web.page.show', $category->slug)."' value='" . $category->id . "' " . $disabled_at . ">" . $space . $category->name . "</option>";
         $this->cat_list_parent($category->id, $space, $selected_id, $disabled, $categories_all);
     }
 }
}

Step 4: Displaying the Category Dropdown in a Blade View:

In your Blade view, use the following code to display the hierarchical category dropdown:

@php
 $selected_id = [old('parent_id', $category->parent_id ?? 0)];
@endphp
<select name="parent_id">
 <option value="0">Select Parent</option>
 {!! (new \App\App\Models\Category())->cat_list($parent_id = 0, $space = '', $selected_id, $disabled = 0) !!}
</select>

Conclusion:
Organizing product categories with a multi-level parent-child relationship enhances the user experience and makes content management more intuitive. With Laravel's elegant Eloquent ORM and Blade templating engine, implementing this feature becomes straightforward. By following the steps outlined in this blog post, you'll be able to create a dynamic and hierarchical category system for your Laravel application, providing a solid foundation for efficient content organization.

Leave A Comment