mafortis
mafortis

Reputation: 7138

Laravel 5 multi level category

i currently i have 2 tables category & subcategory and everything works just fine, but i need another level of sub category which will be like category->sub->sub for that matter i tried to find a reasonable solution and i end up with bunch of packages to handle that for me.

now the question is

  1. do i have to delete my category tables and their relations to my another modes before i try any package or i should just add package top of my current tables?
  2. what is the best package for my purpose base on your experience?

thanks in advance.

Upvotes: 3

Views: 5130

Answers (1)

Sovon
Sovon

Reputation: 1824

You don't need to depend on packages to implement this.

You can design your categories table like following:

|----------|------------|---------------|
|    id    |    name    |  category_id  |
|----------|------------|---------------|

Here category_id is nullable field and foreign key referenced to id of categories table.

For category category_id field will be NULL and for sub-category category_id will be it's parent category id. For sub sub category, category_id will be parent sub category id.

In model, you can write relation like following:

Category.php

/**
 * Get the sub categories for the category.
 */
public function categories()
{
    return $this->hasMany(Category::class);
}

Now you can get your sub categories like $category->categories.

N.B: You don't need the subcategory table, Only one table will do the work.

Update- Show product categories

Update Category.php:

/**
 * Get the parent category that owns the category.
 */
public function parent()
{
    return $this->belongsTo(Category::class);
}

In Product.php:

/**
 * Get the category that owns the product.
 */
public function category()
{
    return $this->belongsTo(Category::class);
}

Now, you need to get product category and all of its parents. It'll be an array of categories from parents to child. Then you can show as you wish.

$category = $product->category;
$categories = [$category];

while (!is_null($category) && !is_null($category = $category->parent)) {
    $categories.unshift($category);
}

// $categories = ['parent category', 'sub category', 'sub sub category' ..]

Show category title sequentially

foreach ($categories as $category) {
    echo $category->title . '<br>';
}

Upvotes: 9

Related Questions