3rgo
3rgo

Reputation: 3153

Pass variable to all views created in a Laravel Controller

I'm organizing my website in sections, which should be visible at first glance on my navigation bar (with an active class on the appropriate link). At the moment, I'm checking for each link in the navbar if the current URL matches the one for the link, but it's only working for 1 URL in each case. It should be like this :

Since all my "sections" use controllers, I was thinking maybe I could implement a way (maybe using the constructor) to pass a variable (section) to all the views returned by a controller, so that my layout can have access to it and set the active class on the proper link.

But I don't want to have to do return View::make('myView')->with('section', $this->section); everytime

Anyone knows how to achieve that ? Thanks.

Upvotes: 0

Views: 771

Answers (2)

Dave
Dave

Reputation: 146

You could also share it between all views, this way its easier to change the segment later if that changes and saves you from having to edit Request::segment(1) in all your views (if you have more)

Use: View::share('section', Request::segment(1));

Then in every view get the value with: $section

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111889

You should use Request::segment(1) to compare it with section.

If your url is article/create and you use Request::segment(1) it will return you article and not article/create

And in fact, you don't have to pass anything to Blade in this case, because it should be visible:

@if (Request::segment(1) == 'article')
  class="active"
@endif

Upvotes: 4

Related Questions