What is best conceptual place to put menu data logic in Laravel. If I use Menu bundle where to put it. In Base_Controller
create additional function or something different?
Note: this answer was written for Laravel 3 and might or might not work with the most recent Laravel 4
My favorite way of creating dynamic menu is achieved by separating the menu part from main layout and injecting the menu data via Laravel's Composer (don't confuse it with Composer PHP package manager, they are different things)
<!-- layouts/default.blade.php -->
<div id="header">Title</div>
<div id="menu">
@render('parts.menu')
</div>
<div id="content"></div>
<div id="footer"></div>
<!-- parts/menu.blade.php -->
<ul>
@foreach($menuitems as $menuitem)
<li>{{ $menuitem->title }}</li>
@endforeach
</ul>
Finally we can inject the variable via composer.
<?php
// application/routes.php
View::composer('parts.menu', function($view){
$view->with('menuitems', Menu::all());
});
This way everytime parts/menu.blade.php
is called, Composer will intercept the view and inject it with $menuitems
variable. It's same as using with
on return View::make('blahblah')->with( 'menuitems', Menu::all() )
Hope it helps :)
Edit: If you don't like to have logics in routes.php
you can put it in start.php
and consider Jason Lewis' way of splitting the start.php
into separate files.
Create a directory in application
called start
and fill it with some files.
+ application [DIR]
\-> + start [DIR]
|-> autoloading.php
|-> composers.php
|-> filters.php
\-> validation.php
Then add these lines of code into the end of your application/start.php
require __DIR__ . DS . 'start' . DS . 'autoloading.php';
require __DIR__ . DS . 'start' . DS . 'filters.php';
require __DIR__ . DS . 'start' . DS . 'composers.php';
require __DIR__ . DS . 'start' . DS . 'validation.php';
You got the idea. Put the composer functions in composers.php.
Read the entire article here: http://jasonlewis.me/article/laravel-keeping-things-organized
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With