dimanche 22 mars 2020

How to create Multi-level dynamic menu using Laravel?

I want to create menus and submenu dynamically in laravel and I've 2 tables in laravel which are :

What I have:

table name: modules

module_id  module_name      link    order
1          menu1            xxxx    1  
2          menu2            xxxx    2
3          menu3            xxxx    3

table name : menus

menu_id  module_id  parent_id  menu_name      link       order   
1        1          0          submenu1       xxxx       1  
2        2          0          submenu1       xxxx       1
3        2          2          submenu2       xxxx       2
4        2          2          submenu3       xxxx       3 
5        2          4          child1         xxxx       1
6        2          4          child2         xxxx       2
7        2          5          subchild1      xxxx       1

So there could be N level of sub menus.

What I did:

I create relation between models like :

class Modules extends Model
{
    protected $table = 'modules';
    protected $primaryKey = 'module_id';    
    protected $fillable = ['*'];    

    public function menuModels()
    {
        return $this->hasMany('App\Models\Menu', 'module_id');
    } 
}


class Menus extends Model
{    
    protected $table = 'menus';
    protected $primaryKey = 'menu_id';

    protected $fillable = ['*'];

    public function menuModels()
    {
        return $this->belongsTo('App\Models\Modules', 'menus', 'module_id');
    }
}

then I fetch the data like :

$menuDatas = ModulesName::with('menuModels')->get()->toArray();

I got the data but the issue which I'm facing is submenu should goes in menu for N level.

Output should be something like :

-menu1
    -submenu1
-menu2 
    -submenu1
    -submenu2
    -submenu3
        -child1
            -subchild1
        -child2
-menu3

How can I fetch the data in proper way and display in view.

can you please guys help me out, I struggle alot in this.

Thanks in Advance



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire