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

Sonu's avatar
Level 3

Some Advice Needed For Menus

I want to make a Menu From Admin Panel Like Home About Contact Etc. And About Us Menu Contains Childs Like About Us Or Team Etc.

The Important Thing i want Main menu can be customized i means if i want to rearrage the elements it can be.. How can i do that trick. and whats should be the table structure ? Thanks

0 likes
10 replies
bashy's avatar

You can use a root_id left_id right_id level schema.

brlebtag's avatar

What @bashy is trying to say it's this:

Schema::create('menu', function(Blueprint $table)
{
    $table->increments('id');
    $table->string('text');
    /*some cool features */
    $table->integer('order'); 
    $table->boolean('is_visible');
    $table->integer('badge');
    /*some cool features */
    $table->integer('parent_id')->unsigned()->nullable()->default(null);
    $table->foreign('parent_id')->references('id')->on('menu');
});)        

A menu table has a references to itself. It means a menu can be submenu(has a parent menu) of another menu. That's probably the best option.

Now you can select all menus and order by parent_id and order field. The first menu will have parent_id null.

The easiest way to generate the menu list will be a recursive function. Recursion is kinda complicated thing when you're starting but easy when you get the idea.

the recursion idea is something like this:

it's a Pseudocode (not a real one...)

function print_menu($node)
{
    for($i =0; $i<$node->children->size(); ++$i)
    {
        echo "<li>".$node->children[$i]."</li>";
        if($node->children[$i]->children > 0)
        {
        echo "<ul>";
        print_menu($node->children[$i]);
        echo "</ul>";
        }
    }
}

echo "<ul>";
print_menu($root);
echo "</ul>";
2 likes
bashy's avatar

The left_id / right_id also allows for ordering so orderBy('left_id', 'ASC') will return them in order (which you show in the backend), you can add a sort function in JS.

kazehaya's avatar

@sonu You could also use a package for this like Baum for example. which also has good documentation.

Sonu's avatar
Level 3

i implemented a drap drop functionality.

kazehaya's avatar

@sonu Looks great! how did you manage to get the drag and drop working with multiple levels deep? Im trying to find a solution for this for some time now. Mind sharing how you did it? :)

1 like

Please or to participate in this conversation.