Reputation: 10913
I want to build a menu from an array in Laravel. What I'm currently doing is putting the array in a view
$menu = ['home', 'users' => ['create users' , 'update user', 'activity log']];
and then looping through it to generate the menu:
<section>
<!-- Left Nav Section -->
<ul class="left">
<li class="divider"></li>
@foreach($menu as $key => $nav)
<li class="has-dropdown">
<a href="#" class="active">{{ $key }}</a>
<ul class="dropdown">
@foreach($nav as $subnav)
<li>
<a href="">{{ $subnav }}</a>
</li>
@endforeach
</ul>
</li>
@endforeach
</ul>
</section>
Is there any other way that I can achieve the same result without putting the data in the view?
I also tried creating a constructor function in the controller:
public function __construct() {
$menu = ['home', 'users' => ['create users' , 'update user', 'activity log']];
return $menu;
}
But I guess that is not how it works. I appreciate any ideas on how I can go about this. Thanks in advance
Upvotes: 3
Views: 3136
Reputation: 11553
View composers to the rescue!
They are executed every time before a view is rendered, so you can use this to pass standard data to them.
Upvotes: 2
Reputation: 18665
If you're using controller layouts you can bind data to the layout from within the constructor. Just make sure you call the parent constructor first so that the layout is instantiated properly.
public function __construct()
{
parent::__construct();
$this->layout->menu = ['home', 'users' => ['create users' , 'update user', 'activity log']];
}
That will bind a $menu
variable to the layout, and will also be available to any nested views that are used with Blades @include
.
Upvotes: 1
Reputation: 301
Have a look at view composers: http://www.laravel.com/docs/views#view-composers
Upvotes: 0