How to show categories in header

I am using laminas-mvc, I need a way to fetch categories from DB and show in header file, means in each page I need categories. Thank you

It is a very good question to fetch categories from a database. Fetching of categories is done in different ways. It is done via using a third-party tool as well like Sphinx or ElasticSearch. But where do you want to show the categories on your page, left navigation, top navigation, right navigation or bottom navigation? Or do you just want to show some data of categories without any linking? Thanks!

Do you use an ORM like Doctrine? Or do you use laminas/laminas-db? How does your model look like? Is it just a loose category or belongs the category to another entity? Like articles can have many categories, e.g.

We need a little more information about what you want to do. If you want categorie data in your header, fetch it in your controller and give the category entity to the view. What exactly is the problem?

I need to populate categories dropdown after fetching from DB in the header file.

I am using laminas-db, since header of the website does not change only controller and actions change I do not want to fetch categories in each controller instead I want to do it in a place only once but available should be available on all pages. don’t tell me to put in session.

So if you want to, you could use a controller plugin that encapsulates fetching and caching category data for you. Another possible way could be using a view helper, that fetches and caches category data and displays it in the view. The latter, however, is rather bad style, as it circumvents the principle of doing the business logic (e.g. reading out data) in a controller and not in the view (or a view helper).

Another possible way could be an event listener that provides data for your view you need in every layout. In the following example, something very similar was done.

Dear @irfan,

The thing which you want to achieve can be done by creating your own custom view helper or by creating your own navigation which fetches data from the database rather than from a config. You can view this old post by @samsonasik here. The changes you need to do most likely will be changing “Zend” to “Laminas”. Thanks!

That sounds like a task for a navigation. You can use a factory to add the categories.