kqxdug
Last Updated: February 25, 2016
·
25.89K
· euantor

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

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

over 1 year ago ·
9972

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

thanks, you could bind it to singleton as well

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

over 1 year ago ·