kqxdug
Last Updated: February 25, 2016
·
23.22K
· euantor
Irnhmv6

Share a variable across views in Laravel

A common situation when building sites is that where you wish to have one element available across all the pages. If that element is static rather than dynamic, that's no problem in Laravel - we simply create a layout and user partials and such. The thing that tends to trip people up though is when the content is dynamic. For example, your navigation. If you're building a site where the navigation may be changed often, you might well be storing it in the database with a Model (as I am in this example). Luckily we can share a variable across all views rather easily:

class Base_Controller extends Controller {

    public function __construct()
    {
        // Build our navigation
        $navlinks = Cache::get('navlinks', function()
        {
            $navlinks = NavLink::with(array('childLinks' => function($query)
                                    {
                                        $query->order_by('position', 'asc');
                                    }))->where('navlink_id', '=', '-1')->order_by('position', 'asc')->get();
            Cache::forever('navlinks', $navlinks);
            return $navlinks;
        });

        View::share('navLinks', $navlinks);
        ...
    }
}

In the above, we are creating the variable $navlinks which we pull from the cache (or if it doesn't exist, pull from the database then cache). The magic happens here though:

View::share('navLinks', $navlinks);

Thanks to this line, we can access our navigation variable within any view we wish via the $navLinks variable.

4 Responses
Add your response

7899
58b64ddba7e9d315453761123991150a

but is it possible to send multiple variables with view::share?

over 1 year ago ·
9972
4b7871e2f0ac8d4e244455f543330e22

Yes, it is possible.

over 1 year ago ·
13710

@lopiar - you can send an object or array instead of a single variable, as another option

over 1 year ago ·
15052
0 sevdfpj6bytkdi xsdrsfyzqbx9xim x7aanfxsbzjgqqolk3uolt0amwtnrew1huw4ch4x kj6f

thanks, you could bind it to singleton as well

App::singleton('navigation', function() { return [ 'title' => 'QPLOT', 'url' => 'qplot.com', ]; }); </code>

over 1 year ago ·