19

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;
Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
nCore
  • 2,027
  • 7
  • 29
  • 57

6 Answers6

52

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.

Gazzer
  • 4,524
  • 10
  • 39
  • 49
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • where can I insert the App::before {code here} line? I mean what file?? Thanks for the clarification :) – melvnberd May 14 '14 at 15:58
  • 2
    found out where, its on the filter.php :) Thanks again for this code! – melvnberd May 14 '14 at 16:09
  • First, thank you very much for this solution. But how would I make it globally available to all controllers/models etc. without having to instantiate it every time I need to use it within my controllers? – Tim Jan 30 '15 at 10:20
  • @Tim, You are most welcome, in the `view` it's already available globally, you can use `$myApp` to access it from any `view` because of `View::share('myApp', $app);` and from any `controller` you may access it using `app('myApp')` or `App::make('myApp')`. – The Alpha Jan 30 '15 at 10:47
  • I understand. But in every controller I have to make 'myApp'. Do I have no possibility doing that just once and access everything from a variable? – Tim Jan 30 '15 at 11:01
  • No possible from `controllers` but from `views` it's available using this approach, but if you instantiate it in your `BaseController` then you may access it using `$this->myApp`, for example, in the `constructor` of `BaseController` you may use something like `$this->myApp = app('myApp') ` and then from child controllers you may use `$this->myApp`. – The Alpha Jan 30 '15 at 11:06
13

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
ajtrichards
  • 29,723
  • 13
  • 94
  • 101
7

Globals are bad. No matter of what, don't use global variables, don't think about using global variables, always think about how can you not use them in your code and still have all you need to have. Here are some reasons, and there are lot more.

Instead, use Laravel power to help you:

Enforce login on your routes creating groups of authenticated routes:

Route::group(array('before' => 'auth'), function()
{
    Route::get('/users/posts', array('as'=>'users.posts.index', 'uses'=>'PostsController@usersPostsIndex'));
});

Now you know that every call to your posts will be authenticated, you can just

class PostsController extends Controller {

    public function usersPostsIndex()
    {
        return View::('users.posts.index')->
                with('user', Auth::user());
    }

}

In your view you'll just have to

{{$user->email}}
{{$user->first_name . ' ' . $user->last_name}}
{{$user->email}}
{{$user->mobile}}

If you don't want to write code to send a User instance to all your views, use the magic of Laravel's View Composers, adding this to your filters.php or creating a composers.php file:

View::composer(array('users.posts.index','users.posts.edit'), function($view)
{
    $view->with('user', Auth::user());
});

And this is now how your views can be used now:

class PostsController extends Controller {

    public function usersPostsIndex()
    {
        return View::('users.posts.index');
    }

    public function usersPostsEdit()
    {
        return View::('users.edit.index');
    }

}

Because Laravel will automatically inject Auth::user() in those views as $user.

Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204
5

I like the View::share method.

Add the following in app/controllers/BaseController.php

class BaseController extends Controller {
    public function __construct() {       
        $name = 'jack';    
        View::share('user', $name); // Share $user with all views
    }
}

and now $user will be available to all your views.

References: Laravel docs, blog post

Justin
  • 26,443
  • 16
  • 111
  • 128
  • still isn't working for me. Am I missing something? It says "undefined variable" – Okiemute Omuta Nov 12 '14 at 15:27
  • You must be, it works and is in the official docs. Make sure you've added `View::share('myvar', 'myvalue');` in the controller, and then in your view make sure you use `$myvar`. – Justin Nov 12 '14 at 17:34
1

I also gave you the same answer in another question you asked, you did not respond. Link

There is no reason to have a separate variable for each property of your $provider model. Simply save the entire model to a variable like this.

if (Auth::check())
{
    $provider = Auth::user();
}

This would generally be done in a route like this.

Route::get('/provider/page/example', function()
{
    $provider = Auth::user();

    return View::make('name.of.view', ['provider' => $provider]);
});

After having done that, you can access the different properties in of the $provider in your views like this.

<p>Your email address is: {{$provider->email}} and your first name is {{$provider->first_name}}</p>

Another option is to use a controller and set this variable only once in the controller, making it accessible from all views using View::share().

class ProviderController extends BaseController {

    protected $provider;

    public function __construct()
    {
        $this->provider = Auth::user();

        View::share('provider', $this->provider);
    }

    public function getIndex()
    {
        return View::make('some.view.name');
    }
}

After having done just this, you can use the $provider variable in your views as shown above using things like $provider->email. You can also use it elsewhere in the controller by using $this->provider.

Community
  • 1
  • 1
Sajan Parikh
  • 4,668
  • 3
  • 25
  • 28
0

You should create an object to do that.

Create a provider object with those properties, email, name, etc and instantiate it and set the properties values, like:

$provider = new Provider();

$provider->email = Auth::user()->email;

And then you save the object in your session:

$_SESSION['provider'] = $provider;

I'm not familiar with Laravel and I don't know if it's a good practice to work directly with the Auth object but a simpler solution would be:

$_SESSION['provider'] = Auth::user();

Also be aware of working with sensitive information on your session :)

  • The only sensitive information there is for now is the users email address. – nCore Nov 13 '13 at 11:50
  • 1
    You should take care with your session information, if you really need it stored, do it. My sessions store the user `id` and when I need it, I request it from database. –  Nov 13 '13 at 11:51