V
V
Vladislav2018-12-12 13:47:19
Yii
Vladislav, 2018-12-12 13:47:19

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',
        ];
    }

getVacancyById method
/**
     * @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

1 answer(s)
M
Maxim Timofeev, 2018-12-12
@Cetch

Trying to get property 'user_id' of non-object?

You are trying to access a property of an object, but it is not an object. Probably here: $vacancy->user_idMost likely, you $vacancycontain null, and accordingly you are trying to do it. null->user_idSo before accessing the property, it is worth checking whether the object is in $vacancyor 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 question

Ask a Question

731 491 924 answers to any question