Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Rahulniit's avatar

All records of Menu with sub menu using Query builder

how to get menu and submenu in view from mysql using query builder?

0 likes
8 replies
Vilfago's avatar

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 ;)

Rahulniit's avatar

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.

Rahulniit's avatar

Yes I have multiple tables one is menu and second one is submenu with menu_ID.

Vilfago's avatar

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.

Rahulniit's avatar

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 ?

Rahulniit's avatar

From now i will must study about eloquent now i am more eager to learn this topic.

Vilfago's avatar

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 ;)

Please or to participate in this conversation.