How to display subcategories in octobercms?

Member

by deron , in category: PHP CMS , 8 months ago

How to display subcategories in octobercms?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by jasen_gottlieb , 8 months ago

@deron 

To display subcategories in OctoberCMS, you can follow these steps:

  1. Ensure that your Category model has a relationship with the Subcategory model. For example, in the Category model, you can define a relationship like this:
1
2
3
public $hasMany = [
    'subcategories' => 'NamespaceToSubcategoryModel',
];


  1. In your controller file, retrieve the categories including their subcategories. For example, you can modify the index method of your controller like this:
1
2
3
4
5
public function index()
{
    $categories = Category::with('subcategories')->get();
    return $this->renderPartial('index', ['categories' => $categories]);
}


  1. Create a partial view file (e.g., index.htm) and iterate over the categories and their subcategories. For example, within your partial view file:
1
2
3
4
5
6
7
8
{% for category in categories %}
    <h2>{{ category.name }}</h2>
    <ul>
        {% for subcategory in category.subcategories %}
            <li>{{ subcategory.name }}</li>
        {% endfor %}
    </ul>
{% endfor %}


  1. Finally, include the partial view in the desired layout or page. For example, in your layout file, you can add {% partial 'index' %} to include the subcategory list.


That's it! Now, when you visit the appropriate page using this layout or view, the subcategories will be displayed under their respective categories.