1

I work with Laravel 8 In my database I have a Menu table with this data:

id  | id_parent | name         | route                 | routename            | term   | active
----------------------------------------------------------------------------------------
1   | NULL      | "Home"       | "/"                   | "home"               | "main" | 1
2   | NULL      | "Storage"    | "/storage"            | "storage"            | "main" | 1
3   | 2         | "Devices"    | "/storage/devices"    | "storage.devices"    | "main" | 1
4   | 2         | "New Device" | "/storage/new-device" | "storage.new-device" | "main" | 1

In my Menu Model I have this code:

public function parent()
{
    return $this->belongsTo('App\Models\Menu', 'id_parent');
}

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

And the function in my Controller looks like this:

static function getMenu($term)
{
    $id_userrole = Auth::user()->id_userrole;
    $route = \Request::route()->getName();
    $menu = Menu::select('name','route','routename')
    ->with('children')
    ->where([['term',$term], ['active',1],['id_parent',null]])
    ->whereHas('access', function($q) use ($id_userrole) {
        $q->where('id_userrole', $id_userrole)
        ->orWhere('id_userrole', 0);
    })
    ->get();
    dump($menu);

    foreach($menu as &$m) {
        $m->isActive = $route == $m->routename ? 1 : 0;
        
        foreach($m->children as &$m2) {
            $m2->isActive = $route == $m2->routename ? 1 : 0;
            $m->isActive = $m2->isActive;
        }
    }
    
    return ApiResource::collection($menu);
}

If i want to get children, the array is empty. This is my output:

{"data":[{"name":"Home","route":"\/","routename":"home","isActive":0,"children":[]},{"name":"Storage","route":"\/storage","routename":"storage","isActive":0,"children":[]}]}

What am I doing wrong?

Jonathan Sigg
  • 306
  • 3
  • 12
  • Try adding `->dd()` before the `->get()` to output the actual SQL query. You can also remove the `whereHas('access')` and the API resource to make sure they aren't the problem. – Thomas Nov 13 '20 at 15:05
  • Try including the `id` column in your select statement: `Menu::select('id', 'name','route','routename')`; – Brian Lee Nov 14 '20 at 05:46

1 Answers1

0

The children relationship will work if model result has id column, you can test like this:

Menu::with('children')->all();

BTW, the parent relationship should be:

public function parent()
{
    return $this->belongsTo('App\Models\Menu', 'id', 'id_parent');
}

And if you want to get children's children's children...

public function descendants()
{
    return $this->children()->with('descendants');
}
CloudyCity
  • 103
  • 1
  • 6