Trying to get property of non-object

Need you help guys i got this error. 1st loop successfully inserted 1st record Dont know why on the 2nd loop of do while it display this error.

PHP Notice – yii\base\ErrorException

Trying to get property of non-object

"$studid = $user->studid;" <-- Highlighted error

Need to query the user table to check the username and get the studid(student ID No. FK)

User Table (userid(pk), username, password, studid(fk))

$model->recipient // client inputted 3 username seperated by comma(glads,venus,nico) in the textInput

//parse the usernames form textInput

$userrecipient = explode(",", $model->recipient); //saved as an array[glads,venus,nico]

        &#036;index = 0;


        


        


        &#036;user = new User();


        &#036;receiver = new Manage(); 


        


        do {


            


            


            &#036;user = User::find()


                    -&gt;where(['username' =&gt; &#036;userrecipient[&#036;index]])


                    -&gt;one();// &lt;-- seems on 2nd loop this command is not executing?

//insert to manage table

        &#036;studid = &#036;user-&gt;studid;//&lt;-- highlighted error &quot;Trying to get property of non-object&quot; on the 2nd insertion


        &#036;receiver-&gt;studid = &#036;studid ; // Student receiver


        &#036;receiver-&gt;msgid = &#036;msgid;


        &#036;receiver-&gt;msg_statusid = 2; // 2= received by default 


        &#036;receiver-&gt;date = date('Y-m-d H:i:s');


        &#036;receiver-&gt;discard = 0;


        &#036;receiver-&gt;unread = 0;


        &#036;receiver-&gt;bounced = 0;


        &#036;receiver-&gt;save();


            


        








            &#036;index++;


        } while (&#036;index &lt; count(&#036;userrecipient));

Remove one from your query:




$user = User::find()->where(['username' => $userrecipient[$index]]);



Tell me if it works thanks

Are there any spaces you forgot to trim around the recipients? That’s what it looks like to me.

removing one does not work

how am i going to trim the spaces? any suggestion?

You can trim whitespaces with trim()

http://php.net/manual/en/function.trim.php

You should also create a way to handle errors if the student is not found.

Try something like this maybe:


foreach($userrecipient as $recipient) 

{

    $user = User::find()

    ->where(['username' => trim($recipient)])

    ->one()

   

   if($user != null)

   {

       Do your thing

   }

   else echo 'Username '.$recipient.' not found.';

}