From what I understand:
View::share('foo','bar');
Will make $foo available in all views.
However, is it correct to say View::share()
can be used only in the __construct()
?
Because from outside __construct()
I can't make it to work.
View::share
should be available anywhere within your application. A common place that it is used is in view composers, but it should be usable within a route or wherever you need it.
View::share('name', 'Steve');
inside a controller's method, $name will be available to all other views? It's just that?
Jun 2, 2013 at 14:06
__construct()
method of your base controller. ;)
Aug 12, 2016 at 21:45
Yes, adding:
View::share('foo','bar');
in your routes.php file will make $foo (with a value of 'bar') available in all views. This is especially useful for something like Twitter Bootstrap's "active" navigation classes. For example, you could do:
View::share('navactive', '');
to make sure the navactive variable is set in all views (and thus won't throw errors) and then when you are making views (in your controller, for example), you could pass:
return View::make('one')->with('navactive', 'one');
and then in your view (preferably some bootstrappy blade template) you can do the following:
<ul class="nav">
@if ( Auth::user() )
<li @if ($navactive === 'one') class="active" @endif><a href="{{{ URL::to('one/') }}}">One</a></li>
<li @if ($navactive === 'three') class="active" @endif><a href="{{{ URL::to('three/') }}}">Three</a></li>
<li @if ($navactive === 'five') class="active" @endif><a href="{{{ URL::to('five/') }}}">Five</a></li>
@endif
</ul>
$navactive
isset()
. Because you've mentioned the navigation marking, another handy solution would be using a plugin that I've built for that very purpose which can be found here: github.com/kfirba/markNavigator
Basically if you want to share the variables through all view, you might first want to create a base route(E.x.:internalController.php
) as a parent class then extend other controllers as a child of it(E.x:childController.php
).
And yeah you will most likely set the view::share('foo', $bar)
in the __constructor()
of the internalController.php
, since it lunches whenever the class is initialized, this way the parent class will serve the variable values to the child classes.
View::share()
?