Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a logged in user-variable in AngularJS+laravel

I'm trying to make a global variable called theUser which contains the userinfo if logged in.

I have tried putting this in my SPA php file:

app.value('theUser', '<?php echo Auth::user(); ?>');

And it works but only after refreshing page. (Login happens via angularjs logic + a $http request to auth/login which returns userinfo if logged in)

In my angular auth app, I have done this:

var login = $http.post("auth/login", sanitizeCredentials(credentials)).success(function(data) {
    theUser = data;
    $rootScope.theUser = theUser;
  });

And that works, but only when the user logs in. If I refresh, theUser is empty. And I can't get these two solutions to work together. I probably need another approach.

All I want is an user variable that I can access from anywhere in my app, which is set if the user logs in, or have been logged in before. Using Laravel 5.1.

Here is my auth app service js: http://pastebin.com/HcdLaZcD

How can I make this work?

like image 571
Terje Nesthus Avatar asked Aug 22 '15 05:08

Terje Nesthus


2 Answers

Why dont you use PHP-Vars-To-Js-Transformer by Laracasts. Then whenever a User logs in, you could set a Session variable auth_user and then get that variable to JavaScript as shown below (in your Laravel AuthController@login):

...
\Session::put('auth_user', \Auth::user());

JavaScript::put([
    'theUser' => \Session::get('auth_user')
]);
...

And when the User logs out: \Session::forget('auth_user');

theUser variable will be available anywhere in your JavaScript (or you can Namespace it also, check the Github link above).

like image 67
amith.gotamey Avatar answered Dec 06 '22 08:12

amith.gotamey


on top of the page under script tag

window.user = <?php echo Auth::user(); ?> 

and

app.value('theUser',window.user);

app.run(function ($rootScope, theUser) {

       $rootScope.theUser = theUser;

});
like image 32
samir Avatar answered Dec 06 '22 08:12

samir