diligent
diligent

Reputation: 2352

Laravel 4 - Where to call View::share

all

I know View::share should be available anywhere within my application, A common place is in my routes.php file.

I am doing this.

1) User login system, after login successfully, share something for all the views.

2) when user click other pages, can use the shared variables.

Ok, my controller.

public function index() {
    $data = array(
        "pageTitle" => "index",
    );

    $privilegeMenu = $this->privilegeApi->getUserPrivilegeByUserId(Session::get('uid'));
    $topMenus = $this->menuApi->getTopMenuById($privilegeMenu);
    $subMenus = $this->menuApi->getSubMenuesById($privilegeMenu);

    View::share('topMenus', $topMenus);
    View::share('subMenus', $subMenus);

    return View::make('home.index',$data);
}

So, because I am using View share, that it is to say, in every other views, I can use topMenus and subMenus now.

But when I click other pages, I got the error: Undefined variable: topMenus.

So, I am so confused what happened? I dive into View::share source code

Laravel have a class named Environment under namespace Illuminate\View.

protected $shared = array();

public function share($key, $value = null)
{
    if ( ! is_array($key)) return $this->shared[$key] = $value;

    foreach ($key as $innerKey => $innerValue)
    {
        $this->share($innerKey, $innerValue);
    }
}

public function shared($key, $default = null)
{
    return array_get($this->shared, $key, $default);
}

And I found when user login successfully, topMenus shared successfully. But when I click other pages, can't topMenus in shared.

It seems everything OK, I am confused. Any one knows ?

Thanks in advanced.

Upvotes: 0

Views: 292

Answers (1)

rmobis
rmobis

Reputation: 27002

This is because your View::share statement is never ran for other routes. In Laravel 4.x, there are quite a few places you could put it where it would be ran every time, but these two are most commonly used:

  1. The easiest and most simple way is to just add it at the end of your app/start/global.php which is ran at the start of every request, for all environments.

  2. The other way is to create a new service provider, make sure it's autoloadable and add it to your app/config/app.php's providers array.

If all you want is share a few views, I'd say it's kinda of an overkill to create a whole new class just for that. If, however, you start noticing your app/start/global.php file is getting too cluttered, I'd recommend you start splitting stuff into service providers.

PS: In Laravel 5, app/start/global.php was removed and you're left only with the second option.

Upvotes: 1

Related Questions