George
George

Reputation: 301

globals in laravel 4

-- sorry, laravel noob here, coming from regular php.

I'm having a problem with a legacy php global i was using. I want to be able to call data from a function in all my views.

Basically, I had a class called loggedInUser which i instantiated with $loggedInUser and I could call an object, for instance, $loggedInUser->user_id.

Right now, I dont know how to move that over. I do not know where/how to have the information defined. I tried doing it in /app/filters.php (before function) which didnt work and in bootstrap/start.php which also didnt work since the Session:: classes could not be called there.

I had this code in filters.php but it seems to not use the class itself, but the each thing i pull, eg ->user_id is a class which should not be the case. How can i make it so that it is just an object? Any idea where it would be best for me to place the code?

App::singleton('loggedInUser', function(){
    $app = new stdClass;
    if (Auth::check()) {
        // Put your User object in $app->user
        //$app->user = Auth::User();
        $loggedInUser = new loggedInUser();
        $user_id = Session::get('uid');
        $app->email = DB::table('app_Users')->where('User_ID', '=', $user_id)->pluck('Email');
        $app->user_id = $user_id;
        $app->display_username = DB::table('app_Users')->where('User_ID', '=', $user_id)->pluck('Username');
        $app->clean_username = DB::table('app_Users')->where('User_ID', '=', $user_id)->pluck('Username_Clean');
        $app->isLogedin = TRUE;
    }
    else {
        $app->isLogedin = FALSE;
    }
    return $app;
});
$app = App::make('loggedInUser');
View::share('loggedInUser', $app);  

Thank you for your input!

Upvotes: 0

Views: 89

Answers (1)

Laurence
Laurence

Reputation: 60048

This is going to be very honest - and I'm sorry if it offends - but there are sooo many issues with your coding logic here alone - it is clear you do not understand Laravel. I would suggest doing some tutorials, I personally recommend Laracasts.com

You bascially dont need ANY of the code you have written. All you need is

View::share('loggedInUser', Auth::user());  

Then in your view

{{{ $loggedInUser->email }}}
{{{ $loggedInUser->display_username }}}

etc...

Some people would say you dont even need the View::share() function - and just do this in your view:

{{{ Auth::user()->email }}}
{{{ Auth::user()->display_username }}}

Upvotes: 2

Related Questions