Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a navigation bar like this.

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

I want to update this dynamically depending on Auth::check(). 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) {
    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 like to hear them too!

like image 922
Aristona Avatar asked May 23 '13 10:05

Aristona


2 Answers

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').

like image 184
Aristona Avatar answered Nov 07 '22 23:11

Aristona


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

like image 33
Maxime Fabre Avatar answered Nov 07 '22 23:11

Maxime Fabre