Aristona Aristona - 1 year ago 54
PHP Question

Binding View::composer to match all views using wildcards?

I have a navigation bar like this.


I want to update this dynamically depending on
. For example, if the user is logged in, "Account" will be changed with "My Profile Page" and child siblings will be replaced with an appropriate array.

I need to do this without editing
View::make calls
in my controllers. It looks pretty bad.

A solution like this is what I'm looking for;

View::composer('home.*', function($view) {
return $view->nest('accountArea', 'home.navigation-loggedIn', null);
return $view->nest('accountArea', 'home.navigation-visitor', null);

If there are better alternatives, I would like to hear them too!

Answer Source

Seems like the wildcards in Laravel works. They're just undocumented as of now.

View::composer('admin.layouts.*', function($view)
     if (Sentry::check()) $view->with('navigation', View::make('admin._partials.navigation'));
     else                 $view->with('navigation', null);

That's what I was looking for.

Update: Here is an alternative solution

You can also bind it to the layout, so all the subviews that extend that layout will benefit from composer.

View::composer('admin.layouts.main_layout', function($view)
     if (Sentry::check()) $view->with('navigation', View::make('admin._partials.navigation'));
     else                 $view->with('navigation', null);

It will bind composers to every view that does @extend('admin.layouts.main_layout').