Laravel Global Variable for All Controller and Views

Hello,

Recently in one of my project we have an admin panel crated with Laravel. There was a requirement to setup global object that can be accessed in all controllers, views, models etc.  Basically it was logged in user object with additional information so we can access details of user in anywhere. Here in this blog I am going to explain how to do this.

First open app -> config -> filters.php file and add following code to it.

App::before(function($request)
{
    // Singleton (global) object
    App::singleton(‘app’, function(){
        $app = new stdClass;
        if (Auth::check()) {
            // Put your User object in $app->user
            $app->user = Auth::User();
            $app->user_access = UserAccess::getAccess($app->user);
        }
        return $app;
    });
    $app = App::make(‘app’);
    View::share(‘app’, $app);
});

As you can see here we are setting filter to setup singleton object and checking if user is logged in or not. If he is logged in we are create global object with name app and setting user information there. Now you can access this in controller with following code. 
$app = App::make(‘app’);
$user = $app->user;
$userAccess = $app->user_access;
And in view you can access in following way.
<div>Welcome {{$app->user->name}}</div>
Or you can use in if condition.
@if($app->user->access_level == “Admin”)
@endif
Same way you can access it in model functions.
$app = App::make(‘app’);
$user = $app->user;
$userAccess = $app->user_access;
Hope this helps you.
This entry was posted in Laravel, MVC, PHP, PHP Framework on by .

About Hiren Dave

Hiren Dave is a software engineer, blogger and consultant with over 9 years of professional experience. He writes code in number of languages. Hiren has a passion for developing web apps, mobile apps and writing books and blog articles about programming. He has a solid experience of startups as he manages products for few startups. He is also passionate about researching and learning new technologies and trends. He has also authored a book Instant Sencha Touch, published by Packt and creator of Video Course "Beginning Laravel" for Packt

Leave a Reply

Your email address will not be published. Required fields are marked *