-1

I want to have Categories with related Subcategories, It must looks like this:

Category: Broth

Subcategory: Chicken broth, Meat broth, Vegetable broth

And I'll create create_categories_table & create_subcategories_table with category_id

I saw some examples with approach that uses: parent_id and child_id but I don't understand that logic, maybe it is required for multiple subcategories?

Could you give me some advices for such scenario?

2
  • 1
    You need to create and define one->many relationship in your Category & Subcategory Model class.You will find this in the official docs also laravel.com/docs/12.x/eloquent-relationships#one-to-many
    – Subha
    Commented yesterday
  • You could even do this with a single categories table and Category model, which is the parent_id (no need for child_id) scenario you mentioned in your question. The relationship logic in Laravel ends up being more complicated, since it would be a recursive relationship, but there's plenty of tutorials available if you search "Laravel recursive relationship". With your suggested setup, you can only do Categories and Subcategories, anything deeper than that wouldn't work (Broth > Vegetable > Vegan wouldn't be possible for example)
    – Tim Lewis
    Commented yesterday

1 Answer 1

-1

You're on the right track! For your use case — categories with related subcategories — using a categories and subcategories table (with category_id) is perfectly fine and easier to understand than using parent_id/child_id.

The parent_id approach is used when both categories and subcategories are stored in the same table, allowing unlimited levels (e.g., category → subcategory → sub-subcategory).

But for simple two-level hierarchies like:

  • Broth

    • Chicken broth

    • Meat broth

Using two separate tables (categories, subcategories) is better and easier to manage.

New contributor
Talha Rashid is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.