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

I have a navigation bar like this.

<li>Account</li> <ul> <li>Register</li> <li>Login/li> ... 

I want to dynamically update it depending on Auth::check() . For example, if the user is logged in, the “Account” will be changed using “My profile page”, and the child brothers will be replaced with the corresponding 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 am looking for;

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

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

+7
source share
3 answers

Looks like wildcards in Laravel’s works. At the moment, they are simply undocumented.

 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 snap it to a layout, so that all sub-points that expand this layout will benefit from the 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 associate composers with every view that @extend('admin.layouts.main_layout') does.

+8
source

You can use View::share('variable', 'value') to exchange a variable in all views.

+3
source

As Ariston says (thanks for the tip!): Wildcards are allowed. Looking at the code, we see how Composers are event listeners, and this section of the documentation states: wildcard event listeners .

Adding a bit more, ultimately, Str::is() uses Events\Dispatcher to detect wild listeners. For example, something like this:

 str_is('namespace::*.view', 'namespace::folder.view') 

In short, I agree that this will not hurt a little informative phrase :)

0
source

All Articles