jeudi 28 mars 2019

Laravel Dynamic Multilevel Drop Down Menu

I tried to solve this for me, but I can not find a solution, if someone could help me I would be very grateful.

I'm building a multilevel dynamic menu,

| id | parend_id | name     | url                 |

| 1  |     0     | Level 1  | /level_one          |

| 2  |     1     | Sublevel | /level_one/sublevel |

| 3  |     0     | Level 2  | /level_two          | 

Model

in my model there are two recursive functions to help me generate the tree:

public function children() {
    return $this->hasMany('App\Menus', 'parent_id', 'id');
}

public static function tree() {
    return static::with(implode('.', array_fill(0, 100, 'children')))->where('parent_id', '=', '0')->get();
}

from the controller I simply create the object and call the function, and everything works fine, but I have tried to solve that when a level no longer has children it does not show my empty array, I can not do it that does not print it inside the object

$components = new Component;
try {
     $menu = $components->tree();
} catch (Exception $e) {}
return response()->json($menu);

I get this:

[
    {
        "id": 1,
        "parent_id": 0,
        "name": "Level 1",
        "url": "/level_one",
        "children": [
            {
                "id": 2,
                "parent_id": 1,
                "name": "Sublevel",
                "url": "/level_one/suvlevel",
                "children": []
            },
         ]
    },
    {
        "id": 3,
        "parent_id": 0,
        "name": "Level 2",
        "url": "/level_two",
        "children": []
    }
]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire