Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Auth::user()->id trying to get a property of a non-object

I'm getting the following error "trying to get a property of a non-object" when I submit a form to add a user, the error is apparently on the first line: Auth::user()->id of the following:

$id = Auth::user()->id; $currentuser = User::find($id); $usergroup = $currentuser->user_group; $group = Sentry::getGroupProvider()->findById($usergroup);  $generatedPassword = $this->_generatePassword(8,8); $user = Sentry::register(array('email' => $input['email'], 'password' => $generatedPassword, 'user_group' => $usergroup));  $user->addGroup($group); 

Any ideas? I've searched for a while and everything I see says this should work fine. My user is logged in using the Sentry 2 authentication bundle.

like image 875
Josh Avatar asked Jul 24 '13 13:07

Josh


People also ask

What is Auth :: user () in Laravel?

Auth::user() — You can check if a user is authenticated or not via this method from the Auth Facade. It returns true if a user is logged-in and false if a user is not. Check here for more about how Facades work in Laravel.

What does Auth :: check () do?

In other words, Auth::check() calls Auth::user() , gets the result from it, and then checks to see if the user exists. The main difference is that it checks if the user is null for you so that you get a boolean value. As you can see, it calls the user() method, checks if it's null, and then returns a boolean value.

What is Auth :: Routes () in Laravel?

Auth::routes() is just a helper class that helps you generate all the routes required for user authentication. You can browse the code here https://github.com/laravel/framework/blob/5.3/src/Illuminate/Routing/Router.php instead.


2 Answers

Now with laravel 4.2 it is easy to get user's id:

$userId = Auth::id(); 

that is all.

But to retrieve user's data other than id, you use:

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

For more details, check security part of the documentation

like image 81
Dr. MAF Avatar answered Oct 09 '22 22:10

Dr. MAF


If you are using Sentry check the logged in user with Sentry::getUser()->id. The error you get is that the Auth::user() returns NULL and it tries to get id from NULL hence the error trying to get a property from a non-object.

like image 24
Altrim Avatar answered Oct 09 '22 20:10

Altrim