Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to get Yii2 object data returned as Json

I am new to the Yii2 framework and PHP. When I try to retrieve a model data from the server as json, I am getting an empty result. But, when I use var_dump, I am getting a non-empty result.

Controller class code:

public function actionIndex() {          
    $client = new Client();
    $client->name = "ajith";
    echo json_encode($client);
}

Model class code:

class Client extends \yii\mongodb\ActiveRecord {
    public static function collectionName() {
        return ['gym', 'client'];
    }

    public function attributes() {
        return ['_id', 'name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'];
    }

    public function rules() {
        return [
            [['name', 'age', 'sex', 'phoneno', 'email', 'address', 'location'], 'safe']
        ];
    }

    public function attributeLabels() {
        return [
            '_id'  => 'ID',
            'name' => 'Name',
            'age'  => 'Age',
            'sex'  => 'Sex',
            'phoneno'  => 'Phoneno',
            'email'    => 'Email',
            'address'  => 'Address',
            'location' => 'Location'
        ];
    }
}

When I use the URL path pathToServer/web/client, I am getting result echoed as {}. Why is it so? I use MongoDB as the database.

like image 622
Kiran Muralee Avatar asked Jul 27 '15 09:07

Kiran Muralee


1 Answers

Import Response class:

use yii\web\Response;
use Yii;

Tell Yii what format do you want as result by setting Yii::$app->response->format before return

public function actionIndex() {    
    Yii::$app->response->format = Response::FORMAT_JSON;        
    $data = ["success" => true, "message" => "Hello World"];
    return $data;
}

Response result:

{
    "success": true,
    "message": "Hello World"
}

You can read about response formats in the yii2-cookbook

like image 147
Oleksandr Pyrohov Avatar answered Sep 23 '22 19:09

Oleksandr Pyrohov