melkhior's avatar

Get all parent categories in a root parent first order

Hey,

At the moment I have a categories table, with id, name and category_id columns.

If category_id is null, that means that category is a root category, otherwise it's some sort of a child category. What I'm trying to get, is to get all parent categories of a category, ordered by the root category first so I use it for a breadcrumb.

How can I do that?

0 likes
3 replies
Braunson's avatar
Braunson
Best Answer
Level 18

@melkhior

So let's assume this is the structure...

Parent Category
    |- Child Category

Which looks like this in the db..

id   |    name              |    category_id (parent category id)
------------------------------------------------
1    |    parent category   |    null
2    |    child category    |    1

What you'll want to do is have the cartegory_id as a foreign key to it's parent. Secondly you will want to setup the proper model relations.. here's an example:

class Category extends Model {
    // Each category may have one parent
    public function parent() {
        return $this->belongsToOne(static::class, 'category_id');
    }

    // Each category may have multiple children
    public function children() {
        return $this->hasMany(static::class, 'category_id');
    }
}

So now that the model relations are defined and you want to display the categories in a view, you'll do something like this to pass them to your view..

view()->composer('homepage', function($view) {
    $view->with('categories', Category::with('children')
            ->whereNull('category_id')
            ->orderBy('name', 'asc')
            ->get());
});

And finally displaying them like so in your blade template..

<ul>
    @foreach ($categories as $parent)
        <li>{{ $parent->name }}
            @if ($parent->children->count())
                <ul>
                @foreach ($parent->children as $child)
                    <li>{{ $child->name }}</li>
                @endforeach
                </ul>
            @endif
        </li>
    @endforeach
</ul>

Hope that helps give you some insight in how to create same table relations :)

2 likes
zymawy's avatar

Cool @Braunson How I Can Learn Such Relations Like This ? That Was Really Helpful And Now For Me !

1 like

Please or to participate in this conversation.