Kamran Ali Kamran Ali - 1 year ago 74
PHP Question

How do I make one to many relationship to same table in Laravel 5?

I have a table called menus.I want to retrieve menus with its child menus.But only parent menus are being retrieved.Child menus result is an empty array.
my table structure is: id | parent_id | name.
My Menu model one to many relationship is:

public function childMenus() {
return $this->hasMany( ‘App\Menu’, ’parent_id’);

public function parentMenus() {
return $this->belongsTo(‘App\Menu’, ‘parent_id’);
My controller Method:
public function index()
$menu = new Menu;
$parent_menus = $menu->where('parent_id', NULL)->get();
$sub_menus = $menu->childMenus()->get();
return View('admin',compact('$parent_menus’, ‘sub_menus’);

When I dive dump sub_menus dd($sub_menus) it returns an empty array.
please anyone help.
thanks in advance.

Answer Source

You're fetching childMenus relation for the newly created Menu object stored in $menu variable that doesn't have any related child menus, while you should fetch chidlMenus for parent menus that already exist in your database.

The easiest way to load parent menus with their child menus is to do the following (notice there is no need to create a new Menu object):

$parent_menus = Menu::with('childMenus')->where('parent_id', NULL)->get();

$parent_menus will now store collecton of all parent menus and each of them will have their child menus stored in childMenus variable. You could iterate parent and child menus with:

foreach ($parent_menus as $parent) {
  foreach ($parent->childMenus as $child) {
    //do whatever you need with the child menu

If all you want is just a collection of all child menus, regardless of what parent they have, just do:

$child_menus = Menu::whereNotNull('parent_id')->get();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download