/** *This function is used to grab navigation bar links stored in a database in a parent/child style * It uses recursion to dynamically search through the links tree i.e It grabs a links children, and children * of children and so on. */ function r_link($parent_links, $fn = "children", $ch_key = "children") { $result = []; foreach ($parent_links as $parent) { $parent_arr = $parent->toArray(); if (!count($parent->{$fn}()->get())) { return [$parent->id => $parent_arr]; } else { $parent_arr[$ch_key] = r_link($parent->{$fn}()->get()); } $result[$parent->id] = $parent_arr; } return $result; }
/** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $links = (new \App\Link())->all(); dd(r_link((new \App\Link())->where('parent_id', '0')->get())); return view('panel.configs.links.all', compact('links')); }