Reputation: 3932
I'm new to Laravel (relatively new to the MVC concept in general) and have watched hours of tutorials and read many others, but there is a simple common task that has eluded me: what is the best way to reuse the same basic elements in a system (say, CMS) across controllers?
Scenario:
I have a content management system, and want to use a different controller for each type of function: e.g. a posts controller for manipulating posts, a users controller for managing users, a menu controller for menu items, etc. Most tutorials recommend this type of workflow.
However, in the actual CMS front-end, I have many common elements that are dynamic (come from the DB) but still need to be displayed across all controllers. For example, the menu (comes from the DB), the current user's details (user name and relevant buttons in accordance with permissions), etc. Displaying it to the user (front-end) is easy enough with Blade, but I can't figure out the best way to do this in the back-end.
For example, if each controller separately gets the menu from the DB, that's a (lack of) code reuse nightmare. On the other hand, there doesn't appear to be a central place from where I can insert this code and pass it onto the view across all controllers. I'm sure that the Laravel developers have thought of this extremely common scenario. What is the best way to implement it?
Upvotes: 3
Views: 2907
Reputation: 153150
This is exactly what View Composers are for!
View Composers allow you to register a callback that is executed before a specific view is rendered. Usually you register them in a Service Provider. You can use the existing AppServiceProvider
or create a new ComposerServiceProvider
for that.
This would be a very basic example for the view with name menu
public function boot(){
View::composer('menu', function($view){
$menu = DB::table('menu')->get();
$view->with('menu', $menu);
});
}
You could also specify a class that contains the composer logic. Read more about that in the docs
Upvotes: 4
Reputation: 1173
You can View::share
the variable in your Base Controller that extends the other Controllers like this:
protected $variable;
public function __construct()
{
$this->variable= Model::all();
View::share('variable', $this->variable);
}
Then just use $this->variable
in the other controllers that extend the Base Controller to get your variable.
Another thing you might try is to register a singleton and use this approach instead
App::before(function($request)
{
App::singleton('variable', function(){
$variable= Model::all();
return $variable;
});
Then use $variable= app('variable');
in your Controllers.
Upvotes: 1