Home > Mobile >  Laravel set null on empty array
Laravel set null on empty array

Time:04-14

i have something data like this json data

my problem is, how to set children to null if there is no data children.

Menu Parent model

Menu children Model

Controller

CodePudding user response:

Try this

$data[] = [
    'id' => $men->id,
    'title' => $men->title,
    'icon' => $men->icon,
    'children' => (count($men->menuchild) > 0) ? $men->menuchild: null,
    ];

CodePudding user response:

I suggest using the following code: ‌

$menus = Menuparent::all();

$data = [];

foreach ($menus as $menu){
    $data[] = [
        'id' => $menu->id,
        'title' => $menu->title,
        'icon' => $menu->icon,
        'children' => (count($menu->menuchild) > 0) ? $menu->menuchild: null,
    ];
}

return response()->json([
    'data' => $data
]);
  • Related