Answer the question
In order to leave comments, you need to log in
Trying to get property 'user_id' of non-object?
There is an action that should delete a record from the database.
It accepts the post id sent by the post method.
After the call, it returns an error, but the delete() method fires.
Where is the mistake?
/**
* @return string
*
* Delete vacancy action
*/
public function actionDelete()
{
/* @var $currentUser User */
$currentUser = Yii::$app->user->identity;
if(Yii::$app->user->isGuest || $currentUser->isUser()) {
return $this->goHome();
}
$model = new Vacancy();
Yii::$app->response->format = Response::FORMAT_JSON;
// получаем id поста, на который пожаловались
// по методу post
$id = Yii::$app->request->post('id');
// находим вакансию
$vacancy = $model->getVacancyById($id);
// на всякий случай, проверяем, является ли
// пользователь автором вакансии
if($currentUser->getId() != $vacancy->user_id ) {
return $this->goHome();
}
if($vacancy->delete()) {
return $this->redirect(Url::to(['/user/profile/view', 'id' => $currentUser->getId()]));
}
return [
'success' => false,
'text' => 'Error',
];
}
/**
* @param $id
* @return array|null|\yii\db\ActiveRecord
*
* get vacancy by id
*/
public function getVacancyById($id)
{
return $this->find()->where(['id' => $id])->one();
}
Answer the question
In order to leave comments, you need to log in
Trying to get property 'user_id' of non-object?
$vacancy->user_id
Most likely, you $vacancy
contain null, and accordingly you are trying to do it. null->user_id
So before accessing the property, it is worth checking whether the object is in $vacancy
or not equal to null, and sometimes checking the instance of which particular class in the variable.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question