user2840318
user2840318

Reputation: 1127

Laravel - rendering inside layout (from controller or ...?)

I have setup a general layout for all my views - all fine.

Now, I would like to get some information from database to put in the header, which is part of the layout.

At the moment, the only way I can find out is something like:

// OneControler.php
static public function hello()
{
$data['hey'] = 'heeey';
return View::make('layouts.partial.nav', $data);    
}

And from inside the layout:

// master.blade.php
...
{{ OneController::hello() }}
...

This works fine but... I think there must be another way? I don't think loading a controller from inside the view/layout is the best way to do this?

Upvotes: 0

Views: 110

Answers (2)

Ben Bos
Ben Bos

Reputation: 2371

If you want to define a variable for all views you can also use share:

View::share('name', 'Steve');

In your view or layout:

{{ $name }}

Upvotes: 1

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

You can use View Composers to help you with this:

View::composer(array('your.first.view','your.second.view'), function($view)
{
    $view->with('count', User::count());
});

Then in your view your.first.view or your.second.view, or even your layout you can just:

{{ $count }}

In the array of views, you put the name of the view:

View::composer(array('layouts.partial.nav') ...

or you can just set it to all views:

View::composer(array('*') ...

Upvotes: 2

Related Questions