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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With