Dan Murfitt
Dan Murfitt

Reputation: 1039

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

I'm just running through the process of upgrading my app to Laravel 5. I was using the Laravel 4 user authentication library, along with my own 'Profile' model, for storing user profile information, defined like this:

User model:

class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract {

    //...
    public function Profile()
    {
        return $this->hasOne('Profile'); 
    }
    //..

}

Profile model:

class Profile extends Eloquent {

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

}

Previously (when the app was Laravel 4), I would be able to access the profile for the logged in user by loading the user object through the Auth facade:

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

However, since upgrading to Laravel 5 this has been throwing a Trying to get property of non-object error.

I am able to load the profile, via the user, if I load the user object directly through the user model, like this:

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

...but this seems like a long-winded way of doing it.

Is there a better way, or is there something I'm missing? Any help appreciated.

Upvotes: 0

Views: 726

Answers (1)

stef
stef

Reputation: 1528

If it's what I think it is, then you might need to update config/auth.php's model option to be your user model's class name.

This property is the model that laravel's auth driver will use. By default, it is App\User.

Upvotes: 1

Related Questions