Mike Ross
Mike Ross

Reputation: 2972

Yii2 rest api update throws object conversion error

I am working with Yii2 REST api and using Authorisation : Bearer for authentication.

I have a model Event and only 2 actions Create and Update but my Updateaction is not working fine and throws Object Class conversion error.

I am using following code for finding Event model with mixed condition.

public function actionUpdate($id)
{
    $params=$_REQUEST;
    /*Following line throws error */
    $model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id'=> Yii::$app->user->identity]);

    if($model !== null){

        $model->attributes=$params;
        $model->partner_id = Yii::$app->user->id;
        $model->updated_date = time();

        if ($model->save()) {

            $this->setHeader(200);
            echo json_encode(array('status'=>1,'data'=>array_filter($model->attributes)),JSON_PRETTY_PRINT);

        }

    }

}

The error is something like this

Object of class api\modules\v1\models\User could not be converted to string

I cant figure out why it says i have created object of User class.

Upvotes: 0

Views: 475

Answers (3)

Bryant Makes Programs
Bryant Makes Programs

Reputation: 1694

The issue is here:

andWhere(['partner_id'=> Yii::$app->user->identity])

You ARE attempting to convert a user object (Yii::$app->user->identity) to a string. Instead, you need to use the user's id (Yii::$app->user->identity->id) which is a string.

Upvotes: 1

Chetan Sharma
Chetan Sharma

Reputation: 2557

Yii::$app->user->identity

is object you should use

Yii::$app->user->identity->id

so final line will be:

$model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id'=> Yii::$app->user->identity->id]);

Upvotes: 2

Sagar Guhe
Sagar Guhe

Reputation: 1106

The problem is with your andWhere(), you are trying to assign partner_id an object viz. Yii::$app->user->identity, so this is where your code is breaking. And do not use json_encode when you can use Yii's response format Response::FORMAT_JSON, so your code would be like:

public function actionUpdate($id)
{
    \Yii::$app->response->format = yii\web\Response::FORMAT_JSON; // formatting response in json format
    $params= json_decode(\Yii::$app->request->rawBody, 1);
    /*Following line throws error */
    $model = Event::find()->where(['event_id'=>$id])->andWhere(['partner_id'=> Yii::$app->user->identity->id]);

    if($model !== null){

        $model->attributes=$params;
        $model->partner_id = Yii::$app->user->id;
        $model->updated_date = time();

        if ($model->save()) {

            $this->setHeader(200);
            return array('status'=>1,'data'=> $model); // you can simply use $model

        }

    }

}

Upvotes: 1

Related Questions