I'm slowly learning Laravel/PHP and am building a menu system for a basic CMS.I have stored the menu in the database as json. This way I can use it for other apps etc.
I am trying to now decode the json and loop through it to display my menu. The new array is an array of objects. My question is:
• How can I iterate through this array? When I attempt to get $item->id it works fine. However, when I then try to get $item->title I get an ErrorException
I'm sure it is something simple. Its driving me nuts! Thanks for take the time to look...
Controller
public function edit($id)
{
$view = View::make('admin.menus.edit');
$view['seo_title'] = Lang::get('admin.system_name') . ' | Edit ' . Lang::choice('admin.menus', 1);
$view['id'] = $id;
$view['menu'] = Menus::find($id);
$view['menuitems'] = json_decode($view->menu->menu_items);
return $view;
}
View with foreach
@foreach( $menuitems as $item)
<h4>{{ $item->title }}</h4>
@endforeach
Json in menu_items col
[{"title":"Title","link":"/test.html","id":"1","children":[{"title":"Title","link":"/test.html","id":"2","children":[{"title":"Title","link":"/test.html","id":"3"}]}]},{"id":"4"},{"id":"5","children":[{"id":"6","children":[{"id":"7"}]}]},{"id":"8"},{"id":"9"}]
Object after json_decode
Array ( [0] => stdClass Object (
[title] => Title
[link] => /test.html
[id] => 1
[children] => Array ( [0] => stdClass Object (
[title] => Title
[link] => /test.html
[id] => 2 [children] => Array (
[0] => stdClass Object (
[title] => Title
[link] => /test.html
[id] => 3
)
)
)
)
)
[1] => stdClass Object (
[id] => 4
)
[2] => stdClass Object (
[id] => 5
[children] => Array ( [0] => stdClass Object (
[id] => 6
[children] => Array (
[0] => stdClass Object (
[id] => 7
)
)
)
)
)
[3] => stdClass Object (
[id] => 8
)
[4] => stdClass Object (
[id] => 9
)
)
Thanks again - I hope someone can spot the error of my ways.