It's depend on your tables...
I can answer
$menus = Menu::with('submenu')->get();
foreach($menu as $menu)
{
echo $menu->name;
foreach($menu->submenu as $submenu)
{
echo $submenu->name;
}
}
But I'm pretty sure it doesn't help you ;)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
how to get menu and submenu in view from mysql using query builder?
It's depend on your tables...
I can answer
$menus = Menu::with('submenu')->get();
foreach($menu as $menu)
{
echo $menu->name;
foreach($menu->submenu as $submenu)
{
echo $submenu->name;
}
}
But I'm pretty sure it doesn't help you ;)
My question is using query builder not by eloquent. Your answer is right using eloquent. I am using MySQL database and I do not know enough about eloquent class. Any one please answer.
Yes I have multiple tables one is menu and second one is submenu with menu_ID.
So sorry, I can't help you... I don't know how to do that properly with the Query Builder.
It's so easy to do with Eloquent, that I think it's a good reason to try it.
But QueryBuilder in a bad way :
$menus = DB::table('menus')->select('id','name','link')->get();
foreach($menus as $menu)
{
$submenu[$menu->id] = DB::table('submenus')->select('id','name','link')->where('menu_id', $menu->id)->get();
}
//return all that mess to view
in your view :
@foreach($menus as $menu)
{{ $menu->name }}
@foreach($submenu[$menu->id] as $submenu)
{{ $submenu->name }}
@endforeach
@endforeach
But you will have a lot of query to your database, and with eloquent you can do all of that with just two...
So my advice is clearly to take that opportunity of this simple exercise to learn the basics of Eloquent.
one thing i need to know using eloquent one need to create model and data will store in model directory not in like mysql DB. Am i correct ?
From now i will must study about eloquent now i am more eager to learn this topic.
Probably there is better people than me to explain this... but I will try.
Your data will always be stored in your DB, as before. Eloquent is just a way to query your database (using Query Builder by the way).
When you wrote query, you know how you organized your database (table, foreign key, relations, etc.). Creating Models class and instructing them with methods is a matter of giving Eloquent the keys to query the database.
So, everything is the same as before, you just have a powerfull assistant to help you. But you have to teach him a little, it's why you must create some models ;)
See https://github.com/Unmd0/X_menu You can Show all menu and submenus and also submenus of submenus and...(all depth) using just one Query builder.
Please or to participate in this conversation.