Back

Menu builder (database)


I want to build a menu where the data comes from database but i don't know where to start. the menu will look like:

Category1
-SubCategory1
-Subcategory2
Category2
-SubCategory1
-SubCategory2

and the content of the database will look like this:

Cat_ID Cat_PArent_id cat_name
1 0 Category1
2 0 Category2
3 1 Subcategory1
4 1 Subcategory2
5 2 Subcategory1
6 2 Subcategory1

JoshuaBedford replied 3 years ago Solution

From what I understand of what you said, you want a menu split into two categories, but can these categories have multiple links in them(same with the subcategories)?

Here is what I am thinking (Pseudocode) this would be in your blade view (possibly a menu partial):

while(Category1 has items){
   display menu item
      if(category1 item has a subcategory1 that belongsTo category1){ //something like $category1->subcategory1->link_url;
          display subCategory1 that belongs to category1;
      }
      if(category1 item has a subcategory2 that belongsTo category1){ //something like $category1->subcategory2->link_url;
          display subCategory2 that belongs to category1;
      }
}
while(Category2 has items){
   display menu item
      if(category2 item has a subcategory1 that belongsTo it){
          display subCategory1 that belongs to category2;
         //
      }
      if(category2 item has a subcategory2 that belongsTo it){
          display subCategory2 that belongs to category2;
      }

}

When I say display I mean that will be the html code of your menu, whether it be a table or div. Within that html code you would use an eloquent relationship to call on that item from the database.

This may not be the most efficient way of doing it, And I hope to learn from other posts here, but this is the basic logic I see behind a database-populated menu. You have to create the menu as normal in html (or bootstrap html or whatever), then use the database to fill it. You can use loops to loop through all that belongTo a category, or loop through all categories.

Hopefully this will get you started at least, If it makes no sense tell me! Jeffrey Way explains each of these things (loops, relationships, etc) much better than I can at Laracasts.


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us