Laravel:Auth :: user() – > id绑定获取一个非对象的属性

我收到以下错误“试图获得一个非对象的属性”当我提交表单添加一个用户,错误显然是在第一行:Auth :: user() – > id以下:

$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); 

有任何想法吗? 我search了一段时间,我看到的一切都应该工作正常。 我的用户使用Sentry 2authentication包进行login。

如果您使用Sentry请使用Sentry::getUser()->id检查login用户。 你得到的错误是Auth::user()返回NULL,它试图从NULL获得id,因此错误trying to get a property from a non-object

做一个validation::检查()之前,以确保你已经login:

 if (Auth::check()) { // The user is logged in... } 

再见

现在用laravel 4.2很容易得到用户的id:

 $userId = Auth::id(); 

就这些。

但是,要检索id以外的用户数据,请使用:

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

有关更多详细信息,请查看文档的安全性部分

id是protected ,只需在你的/models/User.php添加一个公共方法/models/User.php

 public function getId() { return $this->id; } 

所以你可以打电话给它

 $id = Auth::user()->getId(); 

记住总是testing用户是否login…

 if (Auth::check()) { $id = Auth::user()->getId(); } 

Auth::user()函数中检查你的route ,获取Auth :: user()数据的函数应该在web中间件Route::group(['middleware' => 'web'], function () {});

使用Illuminate \ Support \ Facades \ Auth;

在class上:

 protected $user; 

这个代码对我很有用

在构build中:

 $this->user = User::find(Auth::user()->id); In function: $this->user->id; $this->user->email; 

等等..

你的问题和代码示例有些模糊,我相信其他开发人员正在关注错误的东西。 我正在Laravel中创build一个应用程序,使用在线教程来创build一个新的用户和身份validation,并且似乎已经注意到,当您在Laravel中创build一个新用户时,不会创buildAuth对象 – 用于获取(新)login用户的ID在应用程序的其余部分。 这是一个问题,我相信你可能会问。 我在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); 

不应该有创造和authentication,但我不知道还有什么要做。