Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MrBakieness's avatar

morphToMany relationship

I have 2 models in my app Category and SubCategory. A sub category can have many parents with it being either a Category or another SubCategory. So when trying to get the parents of a SubCategory i have set up the relationship as followed in the SubCategory:

public function parents(): morphToMany
    {
        return $this->morphToMany(
            Category::class,
            'parent',
            'sub_category_parent',
            'sub_category_id',
            'parent_id'
        );
    }

So the relationship is store in the 'sub_category_parent' table with the following structure:

sub_category_id
parent_id
parent_type

but when i call this relationship i do not get the parents of the given SubCategory

//parents is returned as an empty collection							
$sub = SubCategory::with('parents')->find(1);

I have made sure that the DB has the correct values. the weird thing is if i dd() the following in my parent function

dd($this->morphToMany(
            Category::class,
            'parent',
            'sub_category_parent',
            'sub_category_id',
            'parent_id'
        )->get());

i can actually see the parents.

So any help would be appreciated.

0 likes
2 replies
Mega_Aleksandar's avatar

Hi,

First, a question about the SubCategory - are they the same as their Category parents? If so, you can make a pivot table with parent | child many-to-many relationship. In the left side you would set the parent id (whichever it may be, either the Category or a SubCategory) and on the right you would set all its "child" categories (again, being a Category or SubCategory).

With that pivot in place, you can flag Categories as parent = true|false or top_level = true|false if you need that functionallity to distinguish the main Categories from the rest.

TL/DR - Squish SubCategories to Categories, flag them as top_level (true|false) and add a pivot many-to-many Categories to itself

Best regards,

Aleksandar

1 like
MrBakieness's avatar

@Mega_Aleksandar Yes, a SubCategory and Category are essentially the same thing. The main difference is just a Category cant have a parent but have the top_level would fix that.

I also have a model that can be a child of the SubCategory but not a Category, so i guess when i create this model i just have to check that the Category selected as the parent is not a top level category.

Please or to participate in this conversation.