在Laravel 5中,通过Auth:: user()调用user对象时无法访问相关的雄辩模型


Unable to access related eloquent models when calling the user object through Auth::User() in Laravel 5

我正在将我的应用程序升级到Laravel 5。我正在使用Laravel 4用户身份验证库,以及我自己的"配置文件"模型,用于存储用户配置文件信息,定义如下:

用户模式:

class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract {
    //...
    public function Profile()
    {
        return $this->hasOne('Profile'); 
    }
    //..
}

概要模型:

class Profile extends Eloquent {
   //...
   public function User()
   {
       return $this->belongsTo('User');
   }
   //...
}

以前(当应用程序是Laravel 4时),我将能够通过Auth facade加载用户对象来访问登录用户的配置文件:

$user = Auth::user();
echo $user->profile->picture;

然而,自从升级到Laravel 5,这已经抛出了一个Trying to get property of non-object错误。

我能够通过用户加载配置文件,如果我直接通过用户模型加载用户对象,像这样:

$user = User::findOrFail(Auth::user()->id)->first();
echo $user->profile->picture;

…但这似乎是一种冗长的方法。

有更好的方法吗,还是我错过了什么?

如果这是我认为的,那么你可能需要更新config/auth.phpmodel选项作为你的用户模型的类名。

这个属性是laravel的验证驱动程序将使用的模型。默认为"App'User"