Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - understanding View::share()

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.

like image 706
user2094178 Avatar asked Jun 01 '13 22:06

user2094178


People also ask

What is view () in Laravel?

What are the views? Views contain the html code required by your application, and it is a method in Laravel that separates the controller logic and domain logic from the presentation logic. Views are located in the resources folder, and its path is resources/views.

How do I move data from one page to another in Laravel?

You can send the variable as route parameter. To do this change your <a> tags like this. Now pass this $course_id to your form view.

How do I return a view in Laravel?

Views may also be returned using the View facade: use Illuminate\Support\Facades\View; return View::make('greeting', ['name' => 'James']); As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory.

Where are views located in Laravel?

Views are stored in the resources/views directory.


2 Answers

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.

like image 159
Jason Lewis Avatar answered Oct 21 '22 13:10

Jason Lewis


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>
like image 9
Matt Pavelle Avatar answered Oct 21 '22 13:10

Matt Pavelle