Skip to content

Instantly share code, notes, and snippets.

@khoatran
Last active May 11, 2016 05:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khoatran/5467624c07002d3274d0 to your computer and use it in GitHub Desktop.
Save khoatran/5467624c07002d3274d0 to your computer and use it in GitHub Desktop.
[Laravel] MenuBuilder to build menu view-object from Laravel config
<?php
return [
'admin_menu' => [
[
'name' => 'Content',
'label_key' => 'launchcms.menu.content',
'children' => [
'content' => [
'name' => 'Content',
'label_key' => 'launchcms.menu.content',
],
'structure' => [
'name' => 'Structure',
'label_key' => 'launchcms.menu.content_type',
'url' => ['route_name' => 'cms_content_type_listing_page']
]
]
]
]
];
<?php
class MenuBuilder
{
public static function buildMenuViewObjectFromConfig($configKey) {
$result = [];
$menu = config($configKey);
foreach ($menu as $mainMenuItem) {
$menuViewObject = self::buildMenuViewObject($mainMenuItem);
if(!empty($menuViewObject)) {
$result[] = $menuViewObject;
}
}
return $result;
}
protected static function buildMenuViewObject($menuItemConfig) {
$result = [];
foreach ($menuItemConfig as $key => $value) {
if($key === 'label_key') {
$result['label'] = trans($value);
}
else if($key ==='children') {
$childrenData = $value;
$childrenDataViewOutput = [];
foreach ($childrenData as $child) {
$childrenDataViewOutput[] = self::buildMenuViewObject($child);
}
$result['children'] = $childrenDataViewOutput;
}
else if($key === 'url') {
$result[$key] = self::buildUrl($value);
}
}
if(!isset($result['url'])) {
$result['url'] = '#';
}
return $result;
}
public static function buildUrl($urlData) {
if(is_string($urlData)) {
return $urlData;
}
if(is_array($urlData)) {
$params = [];
if(isset($urlData['params'])) {
$params = $urlData['params'];
}
if(isset($urlData['route_name'])) {
return route($urlData['route_name'], $params);
}
else if(isset($urlData['action'])) {
return action($urlData['action'], $params);
}
}
return '#';
}
}
<?php
//I use this in method to load menuData by view composer approach. So, I put it in AppServiceProvider
public function boot()
{
view()->composer('layout.main_menu', function ($view) {
$view->with('adminMenu', MenuBuilder::buildMenuViewObjectFromConfig('launchcms.admin_menu'));
});
}
//When render the menu item, you just need to use main property: label, url on the view. That's it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment