Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in laravel 4

Tags:

I was wondering how to do a global variable to save me few lines of copy and pasting this lines. Array it probably and put them in one variable instead? I want to use this variable in other routes.

  $providerEmail = Auth::user()->email;
  $providerName = Auth::user()->first_name;
  $providerSurname = Auth::user()->last_name;
  $providerMobile = Auth::user()->mobile;
like image 662
nCore Avatar asked Nov 13 '13 11:11

nCore


2 Answers

You can create a global singleton within App::before event

App::before(function($request)
{
    // Singleton (global) object
    App::singleton('myApp', function(){
        $app = new stdClass;
        if (Auth::check()) {
            // Put your User object in $app->user
            $app->user = Auth::User();
            $app->isLoggedIn = TRUE;
        }
        else {
            $app->isLoggedIn = FALSE;
        }
        return $app;
    });
    $app = App::make('myApp');
    View::share('myApp', $app);
});

In any view, use it like

if($myApp->isLoggedIn) {
    $myApp->user->email;
    $myApp->user->first_name;
    // ...
}

In any controller, you can use

$myApp = App::make('myApp');
if($myApp->isLoggedIn) {
    $myApp->user->email;
    $myApp->user->first_name;
    // ...
}

Check out Application Events.

like image 126
The Alpha Avatar answered Sep 21 '22 14:09

The Alpha


The best way i've seen is by using a config file.

In your app -> config folder, you create a new file called (for example settings.php)

 app
     config
         settings.php

Then in your configuration file you just created (settings.php) you could add:

<?php

$setting_data['foo'] = 'bar';
$setting_data['bar'] = 'foo';

return $setting_data;

You can then retrieve the config file from your code using:

echo Config::get('settings.foo'); // Will echo bar
echo Config::get('settings.bar'); // Will echo foo
like image 20
ajtrichards Avatar answered Sep 21 '22 14:09

ajtrichards