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.

2 comments:

  1. How can i apply this method in Laarvel 5.3

    ReplyDelete
  2. There is an error on Laravel 5.4:
    PHP Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: Class 'App' not found in /web/site/config/filters.php:2

    ReplyDelete