Accessing Models Globally in Laravel

Published 14th August 2014

Sometimes it can be handy to be able to access a model globally when using Laravel. For example if you want to show the company name as the title in your layout menu. As you will need the company model for every page that uses that layout, loading the model manually for each page is cumbersome. So how do you make the model globally accessable?

It’s actually very simple. You need to add a static method to your model to make it easy to retrieve. Lets assume we have a Company model, then add the following:

public static function current() { return Company::find(Auth::user()->company_id); }

Note that here we are assuming that the logged in user has a company_id that we can use.

We can then simply retrieve the “current” company anywhere we want (when the user is logged in).

{{ Company::current()->name }}

Remember that every time you use the current() method it will execute another database query so don’t go overboard with it.

Alternative using View::share()

Rob Crowe suggested that it might be better to use View Composers for this purpose. While the idea in theory is better, I found that subviews don’t seem to inhert data passed to a layout view.

However I did find an alterntive that worked using View::share() in the App::before filter. It looks like this:

App::before(function($request) { if(Auth::check()){ View::share('current_company', Company::find(Auth::user()->company_id)); } });

This means that the $current_company variable is now available in every view when the user is logged in. Neat.