Hey guys,
I'd like to inject controller and action names automatically to the returned view to add body class, for example:
Controller Users, method showAll():
<body class="users-show-all">
How can I pass variable automatically after any controller is done? I thought about extending Controller class, but it doesn't seem very elegant.
One way would be to name your routes as the class you want to use in your body tag (i.e. users-show-all). Then, in a base controller constructor, you could get the current route and share it globally to all views:
In BaseController.php
public function __construct()
{
$name = Route::current()->getName();
View::share('routeName', $name);
}
Then $routeName
will be available in all views (so long as all controllers extend BaseController and its constructor is being called, and your routes are named). I'd suggest not blindly using $routeName and instead checking if it's set before echoing it out in the body tag.
I found out even easier solution with View::composer()
method. In my /bootstrap/start.php
I put:
View::composer('layout', function ($view) {
$action = Route::current()->getAction()['controller'];
$action = class_basename($action);
$action = snake_case($action);
$action = str_replace(array('@', '_'), '-', $action);
$view->withBodyClass($action);
});
And then in my layout.blade.php
:
<body class="{{{ $body_class }}}">
Works like charm.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community