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
you must check is user loggined ?
Auth::check() ? Auth::user()->id : null
id is protected
, just add a public method in your /models/User.php
public function getId()
{
return $this->id;
}
so you can call it
$id = Auth::user()->getId();
remember allways to test if user is logged...
if (Auth::check())
{
$id = Auth::user()->getId();
}
Check your route
for the function in which you are using Auth::user()
, For getting Auth::user() data the function should be inside web
middleware Route::group(['middleware' => 'web'], function () {});
.
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
.
Your question and code sample are a little vague, and I believe the other developers are focusing on the wrong thing. I am making an application in Laravel, have used online tutorials for creating a new user and authentication, and seemed to have noticed that when you create a new user in Laravel, no Auth object is created - which you use to get the (new) logged-in user's ID in the rest of the application. This is a problem, and I believe what you may be asking. I did this kind of cludgy hack in userController::store :
$user->save();
Session::flash('message','Successfully created user!');
//KLUDGE!! rest of site depends on user id in auth object - need to force/create it here
Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')), true);
Redirect::to('users/' . Auth::user()->id);
Shouldn't have to create and authenticate, but I didn't know what else to do.
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