Code Puch
Code Puch

Reputation: 25

Yii2 Trying to get property of non-object

I'm trying to get data from a model.

$profile = Profile::findOne(['user_id'=>$appointment->user_id]);
$diabetes = $profile->diabetes;

I get an error Trying to get property 'diabetes' of non-object.

Tried to check the availability of data through:

$profile->getAttributes(['diabetes'])

Data present! But I can't use any data from the model in any way. What's my mistake?

Upvotes: 0

Views: 66

Answers (2)

Hemangi khatri
Hemangi khatri

Reputation: 21

If you avoid this error please try bellow code

 $profile = Profile::findOne(['user_id'=>$appointment->user_id]);
 if (!empty($profile)) {
   $diabetes = $profile->diabetes;
 }

Upvotes: 2

Eve
Eve

Reputation: 112

If you want to use findOne please do :

$profile = Profile::findOne($appointment->user_id);

if you want to use find :

$profile = Profile::find()->where(['user_id' => $appointment->user_id])->one();

You can find doc here here Hope this helping

Upvotes: -1

Related Questions