Help with error Trying to get property of non-object

Hello, I’m a newbie to Yii 2 framework and I’m following Yii 2 For Beginners by Bill Keck book and after chapter eleven I get error Trying to get property of non-object in /Applications/MAMP/htdocs/yii2build/frontend/models/Profile.php at line 137

Here is the method and the return statement is what I have in that file at line 137:


   public function getUsername() 

   {

        return $this->user->username;

   }



I’ve looked everywhere and can’t find what is wrong.

Can someone help to solve this error?

Thank you in advance.

It looks like you have nothing in $this->user. Maybe you meant


return $this->username;

?

Hello umneeq, thank you for trying to help me, I tried your suggestion but then i get error Undefined property: frontend\models\Profile::$username

Show all code, please

Thank you user umneeq for all the help solving this issue, you’re the best.

The reason because this error occurred was because I’ve deleted users from DB that had profiles associated with that user. So to prevent this error just add an if statement to the getUsername method like this:


public function getUsername() 

   {

       if($this->user) {

           return $this->user->username;

       }

       return 'User does not exist';

   }

You may consider add this to some other methods to make your app more robust.

Again thanks umneeq for your help.