Thursday, September 24, 2015

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.

1 comment: